前面我们讲了设计模式中的工厂模式,今天我们来学习下策略模式。工厂模式,顾名思义就是生产“产品”的地方,以“生产”为主。策略模式其实就是封装算法的地方,在生活当中我们可能会遇到这么一种情况,在不同的时间或地点执行不同的规则。比如,超市里面会根据不同的节假日进行打折,买满200立减100,积分兑换等活动,那么针对这种情况我们如何来适应这种规则的变化呢?这就是我们今天要讲的策略模式。下面我们来模拟一个收银系统:
收银系统通常分如下几种情况:
1、正常收费
2、打折收费
3、买满指定金额商品后减X元
4、积分兑换
首页,定义一个接口IStrategy让这4种“规则”的类来实现
public interface IStrategy { public abstract void strategy(); }
接下来的4种类分别实现,如下:
public class NormalStrategy implements IStrategy {
@Override
public void strategy()
{
// TODO Auto-generated method stub
System.out.println("正常收费");
}
}
public class RotateStrategy implements IStrategy {
@Override
public void strategy() {
// TODO Auto-generated method stub
System.out.println("折扣收费");
}
}
public class ReturnStrategy implements IStrategy {
@Override
public void strategy() {
// TODO Auto-generated method stub
System.out.println("满300减50收费");
}
}
用一个Context类来维护这个规则配置,代码如下:
public class Context
{
public int type;
public IStrategy strategy;
public Context(int t)
{
this.type = t;
}
public void performStrategy()
{
strategy = StrategyFactory.makeStrategy(type);
this.strategy.strategy();
}
}
public class MyStrategy
{
public static void main(String[] args)
{
Context context = null;
context = new Context(1);
context.performStrategy();
context = new Context(2);
context.performStrategy();
context = new Context(3);
context.performStrategy();
}
}