接口是实现多重继承的途径,而生成遵循某个接口的对象的典型方法就是工厂方法设计模式。工厂方法与直接调用构造器不同,直接调用构造器,会导致对象的生成与对象的使用耦合性太强,使得代码不够灵活,而工厂方法则能够很好的使两者分离。而且工厂方法将完全和接口实现分离,这样也使得我们可以透明的将某个实现替换为另一个实行。
下面是工厂方法的结构:
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类了。