简单工厂和策略模式结合
有一天,军师诸葛亮突然觉得每次都要自己去制作锦囊,然后再给武将,真的好麻烦。最理想的状况当然是,只要对武将说一,说二,说三,武将就会自己去拿走别人已经做好的锦囊去执行。这样诸葛亮就可以轻松很多,也不用担心以后猝死在电脑桌前...不是五丈原上。
这就需要结合简单工厂和策略模式两者的优点了,既不用自己生产锦囊,又只需要命令赵云一个人,简单方便。
于是诸葛亮对军政管理,按照以上的设想,进行了一番大刀阔斧的改革,不亏是军师!
第一步、
军师代码,也就是客户端代码:
package top.lllyl2012.sfactoryandstrategy;
public class Customer {
public static void main(String[] args) {
Context context = null;
context = new Context(1);
context.ContextDoIt();
context = new Context(2);
context.ContextDoIt();
context = new Context(3);
context.ContextDoIt();
}
}
第二步、
现在赵云的活变多了了,他不能像策略模式一样,拿到锦囊就去执行,他要先去简单工厂拿到想要的锦囊。
package top.lllyl2012.sfactoryandstrategy;
public class Context {
private Strategy strategy;
public Context(int index) {
//先去工厂跑一趟,把锦囊拿来
strategy = factory.getStrategy(index);
}
public contextDoIt() {
strategy.doIt();
}
}
第三步、
好吧,先把锦囊造出来,需要已个代表了锦囊的抽象类,以及具体的锦囊类,
package top.lllyl2012.sfactoryandstrategy;
public abstract class Strategy {
public abstract void blow();
}
-----------------------------------------------------------------------------------
package top.lllyl2012.sfactoryandstrategy;
public class SmallFan extends Strategy{
private int gears;
public SmallFan(int gears) {
super();
this.gears = gears;
}
@Override
public void blow() {
System.out.println("small"+gears);
}
}
--------------------------------------------------------------------------------------
package top.lllyl2012.sfactoryandstrategy;
public class MiddleFan extends Strategy{
private int gears;
public MiddleFan(int gears) {
super();
this.gears = gears;
}
@Override
public void blow() {
System.out.println("middle"+gears);
}
}
-------------------------------------------------------------------------------
package top.lllyl2012.sfactoryandstrategy;
public class LargeFan extends Strategy{
private int gears;
public LargeFan(int gears) {
super();
this.gears = gears;
}
@Override
public void blow() {
System.out.println("large"+gears);
}
}
第四步、
来一个生产锦囊的工厂
扫描二维码关注公众号,回复:
2383701 查看本文章
package top.lllyl2012.sfactoryandstrategy;
public class ProductFactory {
public static Strategy getProduct(int type) {
Strategy volumeProduct = null;
switch(type) {
case 1:
volumeProduct = new SmallFan(10);
break;
case 2:
volumeProduct = new MiddleFan(30);
break;
case 3:
volumeProduct = new LargeFan(50);
}
return volumeProduct;
}
}
好了,现在只要给武将下令,他就会自动去工厂取锦囊,然后去办事,方便