接口是實現多重繼承的途徑,而生成遵循某個接口的對象的典型方法就是工廠方法設計模式。工廠方法與直接調用構造器不同,直接調用構造器,會導致對象的生成與對象的使用耦合性太強,使得代碼不夠靈活,而工廠方法則能夠很好的使兩者分離。而且工廠方法將完全和接口實現分離,這樣也使得我們可以透明的將某個實現替換爲另一個實行。
下面是工廠方法的結構:
package Test_1;
interface Service{
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implements1 implements Service{
public void method1(){ System.out.println("Implements1.method1");}
public void method2(){ System.out.println("Implements1.method2");}
}
class Implements1Factory implements ServiceFactory{
public Service getService(){
return new Implements1();
}
}
class Implements2 implements Service{
public void method1() { System.out.println("Implements2.method1");}
public void method2() { System.out.println("Implements2.method2");}
}
class Implements2Factory implements ServiceFactory{
public Service getService(){
return new Implements2();
}
}
public class Factories {
public static void serviceConsumer(ServiceFactory fact){
Service s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args){
serviceConsumer(new Implements1Factory());
serviceConsumer(new Implements2Factory());
}
}
下面是輸出結果:
Implements1.method1
Implements1.method2
Implements2.method1
Implements2.method2
根據不同接口可以提供不同的實現方法,而具體的實現方法也與工廠方法分離。不明白的朋友多敲敲代碼就能夠理解了我覺得。
通過匿名類實現的簡化工廠方法設計模式如下:
interface Service{
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implements1 implements Service{
public void method1(){ System.out.println("Implements1.method1");}
public void method2(){ System.out.println("Implements1.method2");}
public static ServiceFactory Implements1Factory = new ServiceFactory(){
public Service getService(){
return new Implements1();
}
};
}
class Implements2 implements Service{
public void method1() { System.out.println("Implements2.method1");}
public void method2() { System.out.println("Implements2.method2");}
public static ServiceFactory Implements2Factory = new ServiceFactory(){
public Service getService(){
return new Implements2();
}
};
}
public class Factories {
public static void serviceConsumer(ServiceFactory fact){
Service s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args){
serviceConsumer(Implements1.Implements1Factory);
serviceConsumer(Implements2.Implements2Factory);
}
}
通過匿名類使得代碼簡單優雅了許多,而且也不再需要具體的ServiceFactory類了。