工厂模式

[size=medium]工厂模式:“工厂”生活中是生产东西的地方,在Java世界里工厂是生产对象实例的。
工厂的作用:使代码与实现类分离,这样方便我们替换实现。
工厂的动作:选择实现——根据条件提供对应的对象实例。

这几天学习了下《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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值