1 package test_12_1; 2 3 public interface Service { 4 5 void method1(); 6 7 void method2(); 8 }
1 package test_12_1; 2 3 public interface ServiceFactory { 4 5 Service getService(); 6 }
1 package test_12_1; 2 3 public class Implementation1 implements Service { 4 5 public 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 }
1 package test_12_1; 2 3 public class Implementation1Factory implements ServiceFactory { 4 5 @Override 6 public Service getService() { 7 8 return new Implementation1(); 9 } 10 11 12 }
1 package test_12_1; 2 3 public class Implementation2 implements Service { 4 5 @Override 6 public void method1() { 7 8 System.out.println("Implementation2 method1"); 9 10 } 11 12 @Override 13 public void method2() { 14 15 System.out.println("Implementation2 method2"); 16 17 } 18 19 }
1 package test_12_1; 2 3 public class Implementation2Factory implements ServiceFactory { 4 5 @Override 6 public Service getService() { 7 8 return new Implementation2(); 9 } 10 11 }
1 package test_12_1; 2 3 public class Factories { 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(new Implementation1Factory()); 15 16 serviceConsumer(new Implementation2Factory()); 17 } 18 }
结果如下:
Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2