Вместо прямого вызова конструктора.
interface Service {
void method1 ();
void method2 ();
}
interface ServiceFactory{
Service getService ();
}
class Implementation1 implements Service{
Implementation1 (){} // доступ пакетный, конструктор не открытый
public void method1 () {System.out.println (“Imp1 meth1”);}
public void method2 () {System.out.println (“Imp1 meth2”);}
}
class Implementation1Factory implements ServiceFactory {
public Service getService (){
return new Implementation1 ();
}
}
class Implementation2 implements Service{
Implementation2 (){} // доступ пакетный, конструктор не открытый
public void method1 () {System.out.println (“Imp1 meth1”);}
public void method2 () {System.out.println (“Imp1 meth2”);}
}
class Implementation2Factory implements ServiceFactory {
public Service getService (){
return new Implementation2 ();
}
}
public class Factories {//код не зависит от класса,реализующего Servise
public static void serviceConsumer (ServiceFactory fact) {
Service s = fact.getService ();//мы не вызываем конструктор!!!!
// иначе пришлось бы писать Service s = new Implementacion1();
// или Service s = new Implementacion2();
s.method1 ();
s.method2 ();
}
public static void main (String [] args){
serviceConsumer (new Implementation1Factory());
serviceConsumer (new Implementation2Factory ());
}
}
Напечатается: Imp1 meth1
Imp1 meth2
Imp2 meth1
Imp2 meth2