抽象工厂模式与工厂方法模式最大的区别在于:工厂方法模式针对的是一个产品等级结构,而抽象工厂模式需要面对多个产品等级结构。
/* * 标识接口 * */ public interface ProductA { }
/* * 标识接口 * */ public interface ProductB { }
public class ContreteProductA1 implements ProductA { public ContreteProductA1(){ //do someting } }
public class ContreteProductA2 implements ProductA { public ContreteProductA2(){ //do someting } }
public class ContreteProductB1 implements ProductB { public ContreteProductB1(){ //do someting } }
public class ContreteProductB2 implements ProductB { public ContreteProductB2(){ //do someting } }
public interface Creator { /* * 工厂方法 * */ public abstract ProductA factoryA(); public abstract ProductB factoryB(); }
public class ContreteCreator1 implements Creator { @Override public ProductA factoryA() { return new ContreteProductA1(); } @Override public ProductB factoryB() { return new ContreteProductB1(); } }
public class ContreteCreator2 implements Creator { @Override public ProductA factoryA() { return new ContreteProductA2(); } @Override public ProductB factoryB() { return new ContreteProductB2(); } }