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);
}
}