1.目录结构
2.超市促销,商品促销的方式往往有多种方式,有的直接打折,有的满多少返现等,都是不同的策略,根据具体的要求实现不同的营销方式。
3.
各个策略,都是个计算价格的方法cost()。抽象出Strategy接口。
两种策略StrategyA , StrategyB 都要实现接口 Strategy,并实现cost()方法。
Context根据具体的要求,安排调用不同的策略计算价格。
4.具体实现
Strategy.java
public interface Strategy {
public double cost(double num);
}
StrategyA.java
public class StrategyA implements Strategy{
/**
* 打八折
*/
@Override
public double cost(double num) {
// TODO Auto-generated method stub
return num * 0.8;
}
}
StrategyB.java
public class StrategyB implements Strategy{
/**
* 满200 返 100
*/
@Override
public double cost(double num) {
// TODO Auto-generated method stub
if (num >= 200) {
return num - 100;
}
return num;
}
}
Context.java
public class Context {
private Strategy strategy = null;
public Context(Strategy strategy) {
if (strategy != null) {
this.strategy = strategy;
}
}
public double cost(double num) {
// TODO Auto-generated method stub
if (strategy != null) {
return strategy.cost(num);
} else {
return num;
}
}
}
Client.java
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Context context = new Context(new StrategyB());
System.out.println(context.cost(250));
}
}