本文共 2815 字,大约阅读时间需要 9 分钟。
定义:为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类。
抽象工厂模式是工厂方法模式的升级版本,他用来创建一组相关或者相互依赖的对象。他与工厂方法模式的区别就在于,工厂方法模式针对的是一个产品等级结构;而抽象工厂模式则是针对的多个产品等级结构。在编程中,通常一个产品结构,表现为一个接口或者抽象类,也就是说,工厂方法模式提供的所有产品都是衍生自同一个接口或抽象类,而抽象工厂模式所提供的产品则是衍生自不同的接口或抽象类。
Java代码:
interface Service { void method1(); void method2();}interface ServiceFactory { Service getService();}class Implementation1 implements Service { public void method1() { System.out.println("Implementation1:method1()"); } public void method2() { System.out.println("Implementation1:method2()"); }}class Implementation1Factory implements ServiceFactory { public Service getService() { return new Implementation1(); }}class Implementation2 implements Service { public void method1() { System.out.println("Implementation2:method1()"); } public void method2() { System.out.println("Implementation2:method2()"); }}class Implementation2Factory implements ServiceFactory { public Service getService() { return new Implementation2(); }}public class Factories { public static void serviceConsumer(ServiceFactory fact) { Service s = fact.getService(); s.method1(); s.method2(); } public static void main(String[] args) { serviceConsumer(new Implementation1Factory()); serviceConsumer(new Implementation2Factory()); }}
使用内部类的Java代码:
interface Service { void method1(); void method2();}interface ServiceFactory { Service getService();}class Implementation1 implements Service { public void method1() { System.out.println("Implementation1:method1()"); } public void method2() { System.out.println("Implementation1:method2()"); } public static ServiceFactory factory = new ServiceFactory() { public Service getService() { return new Implementation1(); } };}class Implementation2 implements Service { public void method1() { System.out.println("Implementation2:method1()"); } public void method2() { System.out.println("Implementation2:method2()"); } public static ServiceFactory factory = new ServiceFactory() { public Service getService() { return new Implementation2(); } };}public class Factories { public static void serviceConsumer(ServiceFactory fact) { Service s = fact.getService(); s.method1(); s.method2(); } public static void main(String[] args) { serviceConsumer(Implementation1.factory); serviceConsumer(Implementation2.factory); }}
总结
转载地址:http://svxax.baihongyu.com/