策略设计模式(风景区购票示例)
0. UML结构图
![策略模式UML结构图](https://i-blog.csdnimg.cn/blog_migrate/59d3fade55f53b6941a48ef7a466da38.png)
1. 风景区购票示例 Code
1.1 价格策略接口
public interface Strategy {
double getPrice(double originalPrice);
}
1.2 针对婴儿的价格策略
public class BabyStrategy implements Strategy {
@Override
public double getPrice(double originalPrice) {
return 0;
}
}
1.3 针对小孩的价格策略
public class ChildStrategy implements Strategy {
@Override
public double getPrice(double originalPrice) {
return originalPrice * 0.7;
}
}
1.4 针对成年人的价格策略
public class AdultStrategy implements Strategy {
@Override
public double getPrice(double originalPrice) {
return originalPrice;
}
}
1.5 上下文 调用具体的策略
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void printPrice(double price) {
double result = strategy.getPrice(price);
System.out.println("您门票价格为:" + result + "元");
}
}
2. 风景区购票示例 Test
public class StrategyTest {
public static void main(String[] args) {
Strategy childStrategy = new ChildStrategy();
Context context = new Context(childStrategy);
context.printPrice(100);
Strategy adultStrategy = new AdultStrategy();
context.setStrategy(adultStrategy);
context.printPrice(100);
}
}