1 package test_16_4; 2 3 public interface Service { 4 5 void method1(); 6 void method2(); 7 }
1 package test_16_4; 2 3 public interface ServiceFactory { 4 5 Service getService(); 6 }
1 package test_16_4; 2 3 public class Implementation1 implements Service { 4 5 private Implementation1() { 6 7 } 8 9 @Override 10 public void method1() { 11 12 System.out.println("Implementation1 method1()"); 13 } 14 15 @Override 16 public void method2() { 17 18 System.out.println("Implementation1 method2()"); 19 } 20 21 public static ServiceFactory factory = new ServiceFactory() { 22 23 @Override 24 public Service getService() { 25 26 return new Implementation1(); 27 } 28 }; 29 30 }
1 package test_16_4; 2 3 public class Implementation2 implements Service { 4 5 private Implementation2() { 6 7 } 8 9 @Override 10 public void method1() { 11 12 System.out.println("Implementation2 method1()"); 13 } 14 15 @Override 16 public void method2() { 17 18 System.out.println("Implementation2 method2()"); 19 } 20 21 public static ServiceFactory factory = new ServiceFactory() { 22 23 @Override 24 public Service getService() { 25 26 return new Implementation2(); 27 } 28 }; 29 30 }
1 package test_16_4; 2 3 public class Test { 4 5 public static void serviceConsumer(ServiceFactory fact) { 6 7 Service s = fact.getService(); 8 s.method1(); 9 s.method2(); 10 } 11 12 public static void main(String[] args) { 13 14 serviceConsumer(Implementation1.factory); 15 serviceConsumer(Implementation2.factory); 16 } 17 }
结果如下:
Implementation1 method1()
Implementation1 method2()
Implementation2 method1()
Implementation2 method2()