2015-09-07 11:44:36 -06:00
|
|
|
// interfaces/Factories.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
interface Service {
|
|
|
|
void method1();
|
|
|
|
void method2();
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ServiceFactory {
|
|
|
|
Service getService();
|
|
|
|
}
|
|
|
|
|
2015-12-02 09:20:27 -08:00
|
|
|
class Service1 implements Service {
|
|
|
|
Service1() {} // Package access
|
|
|
|
public void method1() {
|
|
|
|
System.out.println("Service1 method1");
|
|
|
|
}
|
|
|
|
public void method2() {
|
|
|
|
System.out.println("Service1 method2");
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
2015-12-02 09:20:27 -08:00
|
|
|
class Service1Factory implements ServiceFactory {
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
public Service getService() {
|
2015-12-02 09:20:27 -08:00
|
|
|
return new Service1();
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-02 09:20:27 -08:00
|
|
|
class Service2 implements Service {
|
|
|
|
Service2() {} // Package access
|
|
|
|
public void method1() {
|
|
|
|
System.out.println("Service2 method1");
|
|
|
|
}
|
|
|
|
public void method2() {
|
|
|
|
System.out.println("Service2 method2");
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
2015-12-02 09:20:27 -08:00
|
|
|
class Service2Factory implements ServiceFactory {
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
public Service getService() {
|
2015-12-02 09:20:27 -08:00
|
|
|
return new Service2();
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class Factories {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
serviceConsumer(ServiceFactory fact) {
|
2015-06-15 17:47:35 -07:00
|
|
|
Service s = fact.getService();
|
|
|
|
s.method1();
|
|
|
|
s.method2();
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2015-12-02 09:20:27 -08:00
|
|
|
serviceConsumer(new Service1Factory());
|
|
|
|
// Services are completely interchangeable:
|
|
|
|
serviceConsumer(new Service2Factory());
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-12-02 09:20:27 -08:00
|
|
|
Service1 method1
|
|
|
|
Service1 method2
|
|
|
|
Service2 method1
|
|
|
|
Service2 method2
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|