2015-11-03 12:00:44 -08:00
|
|
|
// functions/Factories.java
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
interface Service {
|
|
|
|
void method1();
|
|
|
|
void method2();
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ServiceFactory {
|
|
|
|
Service getService();
|
|
|
|
}
|
|
|
|
|
|
|
|
class Implementation1 implements Service {
|
|
|
|
private Implementation1() {}
|
2015-11-03 12:00:44 -08:00
|
|
|
public void method1() { System.out.println("Implementation1 method1");}
|
|
|
|
public void method2() { System.out.println("Implementation1 method2");}
|
2015-06-15 17:47:35 -07:00
|
|
|
public static ServiceFactory factory =
|
|
|
|
new ServiceFactory() {
|
|
|
|
public Service getService() {
|
|
|
|
return new Implementation1();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
class Implementation2 implements Service {
|
|
|
|
private Implementation2() {}
|
2015-11-03 12:00:44 -08:00
|
|
|
public void method1() { System.out.println("Implementation2 method1");}
|
|
|
|
public void method2() { System.out.println("Implementation2 method2");}
|
2015-06-15 17:47:35 -07:00
|
|
|
// Use method reference instead:
|
|
|
|
public static ServiceFactory factory =
|
|
|
|
Implementation2::new; // Constructor reference
|
|
|
|
}
|
|
|
|
|
|
|
|
class Implementation3 implements Service {
|
|
|
|
private Implementation3() {}
|
2015-11-03 12:00:44 -08:00
|
|
|
public void method1() { System.out.println("Implementation3 method1");}
|
|
|
|
public void method2() { System.out.println("Implementation3 method2");}
|
2015-06-15 17:47:35 -07:00
|
|
|
// Use lambda expression instead:
|
|
|
|
public static ServiceFactory factory =
|
|
|
|
() -> new Implementation3();
|
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
// Implementations are completely interchangeable:
|
|
|
|
serviceConsumer(Implementation2.factory);
|
|
|
|
serviceConsumer(Implementation3.factory);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Implementation1 method1
|
|
|
|
Implementation1 method2
|
|
|
|
Implementation2 method1
|
|
|
|
Implementation2 method2
|
|
|
|
Implementation3 method1
|
|
|
|
Implementation3 method2
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|