2011年12月31日土曜日

[设计模式] 策略模式 (Strategy)

1. 场景
算法簇模式, 就是定义了不同的算法族, 并且之间可以互相替换, 此模式让算法的变化独立于使用算法的客户
行为模式之一, 对一系列的算法加以封装, 为所有算法定义一个抽象的算法接口, 并通过继承该抽象算法接口对所有的算法加以封装和实现
具体的算法选择交由客户端决定 (策略)
Strategy 模式主要用来平滑地处理算法的切换

2. 角色
2-1. 环境对象: 策略的外部封装类, 或者说策略的容器类, 该类中实现了对抽象策略中定义的接口或者抽象类的引用
2-2. 抽象策略对象: 接口或抽象类
2-3. 具体策略对象: 封装了实现同不功能的不同算法

3-3. 实例
// 抽象策略对象
public interface Strategy {
    public double cost(double num);
}

// 具体策略对象 A
public class StrategyA implements Strategy{
    public double cost(double num) {
        return num * 0.8;
    }
}

// 具体策略对象 B
public class StrategyB implements Strategy {
    public double cost(double num) {
        if(num >= 200) {
            return num - 50;
        }
        return num;
    }
}

// 环境对象
public class Context {
    private Strategy strategy;
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public double cost(double num){
        return this.strategy.cost(num);
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        double num = 200;
        Context context = new Context(new StrategyB());
        double newNum = context.cost(num);
        System.out.println("实际付账" + newNum + "元");
    }
}

0 件のコメント:

コメントを投稿