英文:Abstract Factory
提供一个创建一系列相关相互依赖对象的接口,而无需指定他们具体的类。抽象工厂为不同产品族的对象创建提供接口。
使用场景:系统需要在不同产品族进行切换
public interface IFacfory {
public IUser createUser();
public IDepartment createDepartment();
}
public interface IUser {
public void insert();
public void getById();
}
public interface IDepartment {
public void insert();
public void getDepartmentById();
}
public class SqlServerUser implements IUser {
@Override
public void insert() {
System.out.println("insert into sqlserver.");
}
@Override
public void getById() {
System.out.println("get user by id from sqlserver.");
}
}
public class SqlServerDepartment implements IDepartment {
@Override
public void insert() {
System.out.println("insert department into sqlserver.");
}
@Override
public void getDepartmentById() {
System.out.println("get department in sqlserver by id.");
}
}
public class AccessUser implements IUser {
@Override
public void insert() {
System.out.println("insert into access");
}
@Override
public void getById() {
System.out.println("get by id from access");
}
}
public class AccessDepartment implements IDepartment {
@Override
public void insert() {
System.out.println("insert department into sqlserver.");
}
@Override
public void getDepartmentById() {
System.out.println("get department in sqlserver by id.");
}
}
//不同产品组使用一个工厂
public class SqlServerFactory implements IFacfory {
@Override
public IUser createUser() {
return new SqlServerUser();
}
@Override
public IDepartment createDepartment() {
return new SqlServerDepartment();
}
}
public class AccessFactory implements IFacfory {
@Override
public IUser createUser() {
return new AccessUser();
}
@Override
public IDepartment createDepartment() {
return new AccessDepartment();
}
}
客户端:
IFacfory facfory = new AccessFactory();
IUser user = facfory.createUser();
IDepartment department = facfory.createDepartment();
user.insert();
user.getById();
department.insert();
department.getDepartmentById();
抽象工厂最大的好处就是便于交换产品系列,具体工厂在代码中一般只出现一次。这就使得改变应用的具体工厂很容易。
第二个好处是他能让具体的创建对象实例和客户端分离,客户端是通过他们的抽象接口操作实例
抽象工厂不太易于拓展,如果需要自增功能,或者自增产品,则需要至少修改三个类,而且实例化的代码是写死在程序中的 , 这样无法避免违背开放-关闭原则。
对于上述问题,可以通过配置文件,结合反射的方式来解决。