第二章策略模式
策略模式的概念很好理解,它将对象和行为分开,将行为定义为 一个行为接口和具体行为的实现,每个if判断都可以理解为一个策略。
比如商场有三种客户,第一种打8折,第二种打9折,第三中不打折,行为接口就是定义一个打折方法,然后所有类来实现这个接口,最后再用环境类来调用策略接口,然后get,set方法,以及策略接口的方法调用,最后在客户类中直接实现方法!
行为接口:打折
public interface AbstractMemberStrategy {
public double calcPrice(double price, int n);
}
高级客户
public class StrategyAdvanceMember implements AbstractMemberStrategy{
@Override
public double calcPrice(double price, int n) {
double money = price * n *0.8;
return money;
}
}
中级客户
public class StrategyIntermediateMember implements AbstractMemberStrategy{
@Override
public double calcPrice(double price, int n) {
double money = price * n*0.9;
return money;
}
}
初级客户
public class StrategyPrimaryMember implements AbstractMemberStrategy{
@Override
public double calcPrice(double price, int n) {
return price * n;
}
}
环境类:选择方法
public class Context {
// 用户折扣策略接口
private AbstractMemberStrategy memberStrategy;
public Context(AbstractMemberStrategy memberStrategy) {
this.memberStrategy = memberStrategy;
}
public double ChargePrice(double price, int n)
{
return memberStrategy.calcPrice(price,n);
}
}
客户界面
public class Client {标签:--------,double,大话,public,AbstractMemberStrategy,Context,new,设计模式,price From: https://www.cnblogs.com/shuangshuangzi/p/16739767.html
public static void main(String[] args) {
// 具体策略类
AbstractMemberStrategy primaryMemberStrategy = new StrategyPrimaryMember();
AbstractMemberStrategy intermediateMemberStrategy = new StrategyIntermediateMember();
AbstractMemberStrategy advanceMemberStrategy = new StrategyAdvanceMember();
// 用户选择不同策略
Context primaryContext = new Context(primaryMemberStrategy);
Context intermediateContext = new Context(intermediateMemberStrategy);
Context advanceContext = new Context(advanceMemberStrategy);
//一本100块钱的书
// 普通会员:100
System.out.println("普通会员的价格:"+ primaryContext.ChargePrice(100,1));
// 中级会员 90
System.out.println("中级会员的价格:"+ intermediateContext.ChargePrice(100,1));
// 高级会员 80
System.out.println("高级会员的价格:"+ advanceContext.ChargePrice(100,1));
}
}