策略模式
定义:
策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
类图:
组成:
1. 抽象策略角色:策略类,通常是一个接口或抽象类
2. 具体策略角色:具体策略类,实现或继承抽象策略角色,包装了具体的算法和行为。
3. 环境角色:持有一个策略类的引用,最终给客户端调用。
应用场景:
1. 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。
2. 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。
3. 对客户隐藏具体策略的实现细节,彼此完全独立。
优缺点:
优点:
1. 策略模式提供了管理相关的算法族的办法。恰当使用继承可以把公共的代码转移到父类里面,从而避免重复的代码。
2. 避免多重条件转移语句。
缺点:
1. 客户端必须要知道所有的策略类,并自行决定使用哪一个策略。
2. 策略模式会造成很多策略类,每个具体策略类都会产生一个新类。
实例
MemberStrategy:抽象角色,会员级别接口
public interface MemberStrategy {
double getDiscount();
} |
GoldenMember:具体策略——黄金会员类
public class GoldenMember implements MemberStrategy{ public double getDiscount() { return 0.05; } } |
StandardMember:具体策略——普通会员类
public class StandardMember implements MemberStrategy { public double getDiscount() { return 1.00; //To change body of implemented methods use File | Settings | File Templates. } } |
MidMember:具体策略——低级会员类
public class MidMember implements MemberStrategy { public double getDiscount() { return 0; //To change body of implemented methods use File | Settings | File Templates. } } |
Product:上下文对象类——商品信息,持有一个会员等级策略接口,通过此对象获取商品的价格,而具体不同的会员得到的价格是不一样的
public class Product {
private String name; private Double basePrice; private MemberStrategy memberStrategy;
public Product(MemberStrategy memberStrategy) { this.memberStrategy = memberStrategy; }
public Product(String name, Double basePrice) { this.name = name; this.basePrice = basePrice; }
public double getFinalPrice() { double rate = memberStrategy.getDiscount(); return basePrice * rate; }
public MemberStrategy getMemberStrategy() { return memberStrategy; }
public void setMemberStrategy(MemberStrategy memberStrategy) { this.memberStrategy = memberStrategy; }
public Double getBasePrice() { return basePrice; }
public void setBasePrice(Double basePrice) { this.basePrice = basePrice; }
public String getName() { return name; }
public void setName(String name) { this.name = name; } } |
Client:客户端对象,具体使用哪些策略都是客户端来组装的
public class Client { public static void main(String args[]) { MemberStrategy memberStrategy = new GoldenMember(); Product product = new Product("xbox", 1800.00); product.setMemberStrategy(memberStrategy);
double finalPrice = product.getFinalPrice();
System.out.println("黄金会员购买xbox的最终价格是" + finalPrice);
} } |