抽象工厂模式特别适合于这样的一种产品结构:产品分为几个系列,在每个系列中,产品的布局都是要同的,在一个系列中某个位置的产品,在另一个系列中一定有一个对应的产品。
这样的产品结构是存在的,这几个系列中同一位置的产品可能是互斥的,它们是针对不同客户的解决方案,每个客户都只择其一。
比如Linux与Windows系统下的界面控件,可以从两个交叉的角度来看,从组件的角度看,可以分为linux的组件和windows的组件;从系统的角度看,可以分为Text组件或其它组件。
Text和Button就是不同的产品系列,客户要么是Windows,要么是Linux,客户的选择都会出现在各产品系列的同一位置。
以下是示例代码:
package
abstractfactory;
public interface ProductA ... {
}
package abstractfactory;
public class ProductA1 implements ProductA ... {
}
package abstractfactory;
public class ProductA2 implements ProductA ... {
}
package abstractfactory;
public interface ProductB ... {
}
package abstractfactory;
public class ProductB1 implements ProductB ... {
}
package abstractfactory;
public class ProductB2 implements ProductB ... {
}
package abstractfactory;
public interface Creator ... {
public ProductA factoryA();
public ProductB factoryB();
}
package abstractfactory;
public class Creator1 implements Creator ... {
public ProductA factoryA() ...{
return new ProductA1();
}
public ProductB factoryB() ...{
return new ProductB1();
}
}
package abstractfactory;
public class Creator2 implements Creator ... {
public ProductA factoryA() ...{
return new ProductA2();
}
public ProductB factoryB() ...{
return new ProductB2();
}
}
package abstractfactory;
public class Client ... {
ProductA pa;
ProductB pb;
public static void main(String[] args) ...{
Client client = new Client();
Creator1 c1 = new Creator1();
client.pa = c1.factoryA();
client.pb = c1.factoryB();
System.out.println(client.pa);
System.out.println(client.pb);
}
}
public interface ProductA ... {
}
package abstractfactory;
public class ProductA1 implements ProductA ... {
}
package abstractfactory;
public class ProductA2 implements ProductA ... {
}
package abstractfactory;
public interface ProductB ... {
}
package abstractfactory;
public class ProductB1 implements ProductB ... {
}
package abstractfactory;
public class ProductB2 implements ProductB ... {
}
package abstractfactory;
public interface Creator ... {
public ProductA factoryA();
public ProductB factoryB();
}
package abstractfactory;
public class Creator1 implements Creator ... {
public ProductA factoryA() ...{
return new ProductA1();
}
public ProductB factoryB() ...{
return new ProductB1();
}
}
package abstractfactory;
public class Creator2 implements Creator ... {
public ProductA factoryA() ...{
return new ProductA2();
}
public ProductB factoryB() ...{
return new ProductB2();
}
}
package abstractfactory;
public class Client ... {
ProductA pa;
ProductB pb;
public static void main(String[] args) ...{
Client client = new Client();
Creator1 c1 = new Creator1();
client.pa = c1.factoryA();
client.pb = c1.factoryB();
System.out.println(client.pa);
System.out.println(client.pb);
}
}