Thinking in Java(7)
1.1 Java工厂模式(不适用匿名类)
public interface Service {
public void method1();
public void method2();
}
public interface ServiceFactory {
public Service getService();
}
import java.io.*;
class Factory1 implements Service{
Factory1() {}
@Override
public void method1() {
// TODO Auto-generated method stub
System.out.println("工厂1生产了1号产品");
}
@Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("工厂1生产了2号产品");
}
}
class Factory1Service implements ServiceFactory {
@Override
public Service getService() {
// TODO Auto-generated method stub
return new Factory1();
}
}
class Factory2 implements Service {
@Override
public void method1() {
// TODO Auto-generated method stub
System.out.println("工厂2生产了1号产品");
}
@Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("工厂2生产了2号产品");
}
}
class Factory2Service implements ServiceFactory {
@Override
public Service getService() {
// TODO Auto-generated method stub
return new Factory2();
}
}
public class Factories1 {
public static void go(ServiceFactory servicefactory) {
Service serv = servicefactory.getService();
serv.method1();
serv.method2();
}
public static void main(String[] args) {
go(new Factory1Service());
go(new Factory2Service());
}
}
1.2 使用匿名类的实现
注意将工厂构造函数设为私有, 个人觉得这种方式很优雅
import java.io.*;
class Factory3 implements Service {
private Factory3() {}
@Override
public void method1() {
// TODO Auto-generated method stub
System.out.println("工厂3生产了1号产品");
}
@Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("工厂3生产了2号产品");
}
public static ServiceFactory factory3 =
new ServiceFactory() {
@Override
public Service getService() {
// TODO Auto-generated method stub
return new Factory3();
}
};
}
class Factory4 implements Service {
private Factory4() {}
@Override
public void method1() {
// TODO Auto-generated method stub
System.out.println("工厂4生产了1号产品");
}
@Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("工厂4生产了2号产品");
}
public static ServiceFactory factory4 =
new ServiceFactory() {
@Override
public Service getService() {
// TODO Auto-generated method stub
return new Factory4();
}
};
}
public class Factories2 {
public static void go(ServiceFactory sf) {
Service serv = sf.getService();
serv.method1();
serv.method2();
}
public static void main(String[] args) {
go(Factory3.factory3);
go(Factory4.factory4);
}
}