策略模式的应用场景:
针对不同的业务,需要有不同的处理方法(或在不同时间应用不同的业务规则),如租车的时候针对不同的门店有不同的消费方法。
代码如下:
public abstract class Cost {
/**
* 定义一个消费行为
*
* @Description: 定义一个抽象类,包含一个消费行为
* @Author: Lenny
* @Date: 2019/8/19
*/
public abstract void cost();
}
/**
* @program: LearningDemo
* @description: 门店A具体的消费算法
* @author: Lenny
* @create: 2019-08-19 20:48
**/
public class StoreA extends Cost{
@Override
public void cost() {
System.out.println("门店A花费的具体实现");
}
}
/**
* @program: LearningDemo
* @description: 门店B具体的消费算法
* @author: Lenny
* @create: 2019-08-19 20:49
**/
public class StoreB extends Cost {
@Override
public void cost() {
System.out.println("门店B花费的具体实现");
}
}
/**
* @program: LearningDemo
* @description: 门店C具体的消费算法
* @author: Lenny
* @create: 2019-08-19 20:50
**/
public class StoreC extends Cost {
@Override
public void cost() {
System.out.println("门店C花费的具体实现");
}
}
/**
* @program: LearningDemo
* @description: 具体消费类
* @author: Lenny
* @create: 2019-08-19 20:52
**/
public class ConcreteCost {
private Cost cost;
public ConcreteCost(Cost cost){
this.cost = cost;
}
public void getConcreteCost(){
cost.cost();
}
public static void main(String[] args) {
ConcreteCost storeACost = new ConcreteCost(new StoreA());
ConcreteCost storeBCost = new ConcreteCost(new StoreB());
ConcreteCost storeCCost = new ConcreteCost(new StoreC());
storeACost.getConcreteCost();
storeBCost.getConcreteCost();
storeCCost.getConcreteCost();
}
}
网友评论