策略模式允许在允许中替换算法。要实现该解决方案,需要将每个算法表示为Strategy(策略)类。然后应用程序委托当前的Strategy类来执行特定于策略的算法。
1、Strategy
下面示例使用Role(充当Strategy)接口来声明策略行为和俩个具体来——Buyer和Seller来实现不同的行为:
Role接口:
package strategy;
public interface Role {
public boolean siSatisfied(Product product, double price);
}
Seller类:希望销售的产品都设置了20%的利润率
package strategy;
public class Seller implements Role{
public boolean siSatisfied(Product product, double price) {
//具有20%的利润
if(price - product.getCost() > product.getCost() * .2){
return true;
}else{
return false;
}
}
}
对于Buyer来说,他要买下此种商品,必须有一个限制额。
package strategy;
public class Buyer implements Role{
private double limit;
public Buyer(double limit){
this.limit = limit;
}
public boolean siSatisfied(Product product, double price) {
if(price < limit && price < product.getCost() * 2){
return true;
}
return false;
}
}
2、context
Context这里是指:管理Role的Person类。Person类与Role接口又一个关联,另外值得注意的是,Role又一个setter和getter方法,它允许一个人的角色在程序执行时发生变化。以后,其它的Role实现对象(如broker(中间)等)都可以被添加。因为它们对特定的子类没有依赖。下面时Person类:
package strategy;
public class Person {
private String name;
private Role role;
public Person(String name){
this.name = name;
}
public Role getRole(){
return role;
}
public void setRole(Role role){
this.role = role;
}
public boolean statisfied(Product product, double price){
//statisfied方法将特定于角色的行为委托给其Role接口。这里多态会选择正确的底层对象。
return role.isSatisfied(product, price);
}
}
其它类:本示例的Product类及执行的Main类:
1、Product
package strategy;
public class Product {
private String name;
private String description;
private double cost;
public Product(String name, String description, double cost){
this.name = name;
this.description = description;
this.cost = cost;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
}
2、Main类
package strategy;
public class Main {
public static void main(String[] args){
Product house = new Product("house", "Three room and a parlor", 200000);
Product laptop = new Product("laptop", "The latest style of lenovo laptop computer", 10000);
Person liLei = new Person("李雷");
Person hanMeimei = new Person("韩梅梅");
liLei.setRole(new Buyer(500000));
hanMeimei.setRole(new Seller());
if(!hanMeimei.statisfied(house, 200000)){
System.out.println("韩梅梅房子不会卖200000。");
}
if(!liLei.statisfied(house, 6000000)){
System.out.println("李雷,觉得如果要花6000000买下那房子,太贵了!");
}
if(liLei.statisfied(house, 390000) && hanMeimei.statisfied(house, 390000)){
System.out.println("他们最终已390000的价格成交了!");
//允许时修改一个对象的行为而不影响它的实现
hanMeimei.setRole(new Buyer(390000));
if(hanMeimei.statisfied(laptop, 11000)){
System.out.println("得到390000,韩梅梅现在花了11000去买进了一台最新款的联系笔记本!");
}
}
}
}
通过实现策略模式,可以在运行时修改一个对象的行为而不影响它的实现。这是软件设计中非常强大的工具。