package Strategy;
public interface Strategy {
public Double getprice(Double standardPrice);
}
class FewStrategy implements Strategy{
public Double getprice(Double standardPrice) {
System.out.println("不打折");
return standardPrice;
}
}
class MainStrategy implements Strategy{
public Double getprice(Double standardPrice) {
System.out.println("打9折");
return standardPrice*0.9;
}
}
class OldFewStrategy implements Strategy{
public Double getprice(Double standardPrice) {
System.out.println("打8.5折");
return standardPrice*0.85;
}
}
class oldStrategy implements Strategy{
public Double getprice(Double standardPrice) {
System.out.println("打8折");
return standardPrice*0.8;
}
}
package Strategy;
//负责主要的策略交互,这样的话,具体的算法和直接的客户分离了
//使算法可以独立于客户端的变化
public class Content {
private Strategy strategy;
//通过get set方法注入
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
//通过构造器注入
public Content (Strategy strategy){
super();
this.strategy=strategy;
}
public void printprice(double s){
System.out.println("报价"+strategy.getprice(s));
}
}
package Strategy;
public class Client {
public static void main(String[] args) {
Strategy s1 = new OldFewStrategy();
Content c = new Content(s1);
c.printprice(1000);
}
}
运行结果: