[size=medium]工厂模式:“工厂”生活中是生产东西的地方,在Java世界里工厂是生产对象实例的。
工厂的作用:使代码与实现类分离,这样方便我们替换实现。
工厂的动作:选择实现——根据条件提供对应的对象实例。
这几天学习了下《Thinking in Java》中“接口”这个章节。觉得该章中关于工厂的设计例子蛮有意思的,参照它写了如下一个例子:[/size]
[size=medium]下面是工厂:[/size]
[size=medium]测试代码:[/size]
[size=medium]运行结果:
Cycle Run
BiCycle Run
TriCycle Run
Cycle Run
BiCycle Run
TriCycle Run[/size]
[size=medium]感觉这样设计工厂有点做作,可能为了强调“接口”吧 :) [/size]
工厂的作用:使代码与实现类分离,这样方便我们替换实现。
工厂的动作:选择实现——根据条件提供对应的对象实例。
这几天学习了下《Thinking in Java》中“接口”这个章节。觉得该章中关于工厂的设计例子蛮有意思的,参照它写了如下一个例子:[/size]
public interface Cycle {
public void run();
}
public class UniCycle implements Cycle {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Cycle Run");
}
}
public class BiCycle implements Cycle {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("BiCycle Run");
}
}
public class TriCycle implements Cycle {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("TriCycle Run");
}
}
[size=medium]下面是工厂:[/size]
public interface CycleFactory {
public Cycle getCycle();
}
public class UniCycleFactory implements CycleFactory {
@Override
public Cycle getCycle() {
// TODO Auto-generated method stub
return new UniCycle();
}
}
public class BiCycleFactory implements CycleFactory {
@Override
public Cycle getCycle() {
// TODO Auto-generated method stub
return new BiCycle();
}
}
public class TriCycleFactory implements CycleFactory {
@Override
public Cycle getCycle() {
// TODO Auto-generated method stub
return new TriCycle();
}
}
[size=medium]测试代码:[/size]
public class FactoryTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
run(new UniCycleFactory().getCycle());
run(new BiCycleFactory().getCycle());
run(new TriCycleFactory().getCycle());
run(new UniCycleFactory());
run(new BiCycleFactory());
run(new TriCycleFactory());
}
public static void run(Cycle cycle){
cycle.run();
}
public static void run(CycleFactory cycleFactory){
Cycle cycle = cycleFactory.getCycle();
cycle.run();
}
}
[size=medium]运行结果:
Cycle Run
BiCycle Run
TriCycle Run
Cycle Run
BiCycle Run
TriCycle Run[/size]
[size=medium]感觉这样设计工厂有点做作,可能为了强调“接口”吧 :) [/size]