package Chapter10;
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
class Implementation1 implements Service {
private Implementation1() {}
public void method1() {
System.out.println("Implementation1 method1");
}
public void method2() {
System.out.println("Implementation1 method2");
}
public static ServiceFactory factory =
new ServiceFactory() {
public Service getService() {
return new Implementation1();
}
};
}
class Implementation2 implements Service {
private Implementation2() {}
public void method1() {
System.out.println("Implementation2 method1");
}
public void method2() {
System.out.println("Implementation2 method2");
}
public static ServiceFactory factory =
new ServiceFactory() {
public Service getService() {
return new Implementation2();
}
};
}
public class Factories {
public static void serviceConsumer(ServiceFactory factory) {
Service s = factory.getService();
s.method1();
s.method2();
}
public static void main(String[] args) {
serviceConsumer(Implementation1.factory);
serviceConsumer(Implementation2.factory);
}
}
运行结果:
其中,用于Implementation1和Implementation2的构造器都可以是private的,并且没有任何必要去创建作为工厂的具名类。另外,经常只需要单一的工厂对象,因此在本例中它被创建为Service实现中的一个static域。
对比java工厂设计模式,采用匿名内部类实现使得代码简洁了许多。
本文介绍了一种使用Java匿名内部类实现工厂模式的方法,通过这种方式,可以显著减少代码量并保持良好的设计模式实践。示例展示了如何创建两个不同的服务实现并通过静态工厂方法提供实例。
231

被折叠的 条评论
为什么被折叠?



