在工廠對象上調(diào)用創(chuàng)建方法,生成接口的某個實(shí)現(xiàn)的對象
通過這種方式,接口與實(shí)現(xiàn)分離
- 方法接口
/**
* 方法接口
*/
public interface Service {
void method1();
void method2();
}
- 工廠方法接口
/**
* 工廠方法接口
*/
public interface ServiceFactory {
Service getService();
}
- 方法實(shí)現(xiàn)
/**
* 實(shí)現(xiàn)類1
*/
public class Impl1 implements Service {
public void method1(){System.out.println("Impl1 method1");}
public void method2(){System.out.println("Impl1 method2");}
}
/**
* 實(shí)現(xiàn)類2
*/
public class Impl2 implements Service{
public void method1(){System.out.println("Impl2 method1");}
public void method2(){System.out.println("Impl2 method2");}
}
- 工廠方法實(shí)現(xiàn)
public class ImplFactory1 implements ServiceFactory {
public Service getService(){
return new Impl1();
}
}
public class ImplFactory2 implements ServiceFactory{
public Service getService(){
return new Impl2();
}
}
- 測試
public class Test {
public static void main(String[] args){
ServiceFactory sf1 = new ImplFactory1();
Service s1 = sf1.getService();
s1.method1();
s1.method2();
ServiceFactory sf2 = new ImplFactory2();
Service s2 = sf2.getService();
s2.method1();
s2.method2();
}
}