匿名内部类工厂模式

xiaoxiao2021-02-28  38

interface Service { void method1(); void method2(); } interface ServiceFactory { Service getService(); } public 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(); } }; } public 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); } }
转载请注明原文地址: https://www.6miu.com/read-2613822.html

最新回复(0)