在使用工厂方法模式时,如果工厂很多,那么在变更子类类型时就要修改多个工厂,复杂且容易出错。一个解决办法就是使用抽象工厂模式,建造一个生产工厂的工厂。
抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
UML图:
代码:
public interface EmployeeDao {
Employee selectById(int id);
}
public class EmployeeDaoMySQLImpl implements EmployeeDao {
@Override
public Employee selectById(int id) {
System.out.println("EmployeeDaoMySQLImpl::selectById");
return new Employee();
}
}
public class EmployeeDaoOracleImpl implements EmployeeDao {
@Override
public Employee selectById(int id) {
System.out.println("EmployeeDaoOracleImpl::selectById");
return new Employee();
}
}
public interface ProductDao {
Product selectById(int id);
}
public class ProductDaoMySQLImpl implements ProductDao {
@Override
public Product selectById(int id) {
System.out.println("ProductDaoMySQLImpl::selectById");
return new Product();
}
}
public class ProductDaoOracleImpl implements ProductDao {
@Override
public Product selectById(int id) {
System.out.println("ProductDaoOracleImpl::selectById");
return new Product();
}
}
public interface Factory {
EmployeeDao getEmployeeDao();
ProductDao getProductDao();
}
public class MySQLFactory implements Factory {
@Override
public EmployeeDao getEmployeeDao() {
return new EmployeeDaoMySQLImpl();
}
@Override
public ProductDao getProductDao() {
return new ProductDaoMySQLImpl();
}
}
public class OracleFactory implements Factory {
@Override
public EmployeeDao getEmployeeDao() {
return new EmployeeDaoOracleImpl();
}
@Override
public ProductDao getProductDao() {
return new ProductDaoOracleImpl();
}
}
客户端示例:
public class Client {
public static void main(String[] args) {
System.out.println("use MySQL");
Factory factory = new MySQLFactory();
factory.getEmployeeDao().selectById(1);
factory.getProductDao().selectById(1);
System.out.println("use Oracle");
factory = new OracleFactory();
factory.getEmployeeDao().selectById(1);
factory.getProductDao().selectById(1);
}
}