工厂设计模式(匿名类)

来源:互联网 发布:java ocr识别 验证码 编辑:程序博客网 时间:2024/06/08 10:01
package innerclasses;
interface Service{
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implementationa1 implements Service{
private Implementationa1(){}
public void method1(){
System.out.println("Implementation1 method1");
}
public void method2(){
System.out.println("Implementation1 method2");
}
public static ServiceFactory factory = 
new ServiceFactory() {
@Override
public Service getService() {
// TODO Auto-generated method stub
return new Implementationa1();
}
};
}
class Implementation2 implements Service{
private Implementation2(){}
public void method1(){System.out.println("Implementation2 method1");}
public void method2(){System.out.println("Implenentation2 method2");}
public static ServiceFactory factory =
new ServiceFactory() {

@Override
public Service getService() {
// TODO Auto-generated method stub
return new Implementation2();
}
};
}
public class Factories {
public static void serviceConsumer(ServiceFactory factory){
Service service = factory.getService();
service.method1();
service.method2();
}
public static void main(String[] args){
serviceConsumer(Implementationa1.factory);
serviceConsumer(Implementation2.factory);
}

}

输出

Implementation1 method1
Implementation1 method2
Implementation2 method1
Implenentation2 method2


现在用于Implementation1 和implementation2的构造器都可以是private的,

并且没有任何必要去创建作为工厂的具名类。

另外,你经常只需要单一的工厂对象,因此在本例中它被创建为Service实现中的一个static域。

这样所产生语法也更具有实际意义。

原创粉丝点击