/*
*
* 策略模式(Strategy)
* 如同LayoutManager和具体的布局管理器的关系,在抽象策略类中定义方法,在具体策略子类中实现。
* 客户代码根据不同的需要选择相应的具体类,例如电子商务中多种价格算法。
* 一种策略一旦选中,整个系统运行期是不变化的
*/
package model;
public class TestStrategy {
public static void main(String[] args) {
Strategy s1 = new May1Strategy();
Strategy s2 = new June1Strategy();
Book b = new Book(100);
b.setS(s2);
System.out.println(b.getPrice());
}
}
class Book {
Strategy s;
public Book(double price) {
this.price = price;
}
private double price;
public void setS(Strategy s) {
this.s = s;
}
public double getPrice() {
return price * s.getZheKou();
}
}
interface Strategy {
double getZheKou();
}
class May1Strategy implements Strategy {
public double getZheKou() {
return 0.8;
}
}
class June1Strategy implements Strategy {
public double getZheKou() {
return 0.7;
}
}