含义

网上一位大神博客里面的话:

策略模式,又叫算法簇模式,就是定义了不同的算法族,并且之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

维基百科里面的定义:

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm’s behavior to be selected at runtime. The strategy pattern defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family. Strategy lets the algorithm vary independently from clients that use it.

翻译过来大意就是:这种设计模式可以使程序在运行时可以选择一种算法。它通过定义一个算法的family,并且封装每一个算法,且使这个family里面的各个算法之间可以相互代替(interchangeable)。这种算法的使用依赖于客户端的使用。

UML

可以看出来,策略模式的构成很简单,无非是要一个需要构建的对象,和几个具体的策略。

代码

package com.ans;

import java.util.ArrayList;
import java.util.List;

//付费方式
interface PayStrategy {
    // 参数是原价,返回实际应付的价钱
    public double payMoney(double rawPrice);
}

// 以下是不同策略的实现

// 正常策略
class NormalStrategy implements PayStrategy {
    public double payMoney(double rawPrice) {
        return rawPrice;
    }
}

// 节假日八折
class FestivalStrategy implements PayStrategy {
    public double payMoney(double rawPrice) {
        return rawPrice * 0.8;
    }
}

// 之后还可以添加 n 中策略...

class AnniversaryStrategy implements PayStrategy {
    public double payMoney(double rawPrice) {
        return rawPrice*0.5;
    }
}

class Customer {
    private List<Double> moneyOfDrinks;// 买的东西所花费的钱
    private PayStrategy pstrategy;

    public Customer(PayStrategy pstrategy) {
        this.pstrategy = pstrategy;
        this.moneyOfDrinks = new ArrayList<Double>();
    }

    // 累加花钱数
    public void add(double price, int quantity) {
        moneyOfDrinks.add(pstrategy.payMoney(price * quantity));
    }

    public void printBill() {
        double sum = 0;
        for (Double bills : moneyOfDrinks) {
            sum += bills;
        }
        System.out.println("总共花费: " + sum);
    }

    public void setStrategy(PayStrategy pstrategy) {
        this.pstrategy = pstrategy;
    }

}

public class TestStrategyPattern {
    public static void main(String[] args) {

        //第一位顾客
        Customer customer1 = new Customer(new NormalStrategy());
        customer1.add(50, 3);
        customer1.printBill();
        //现在换了策略了
        customer1.setStrategy(new FestivalStrategy());
        customer1.add(50, 2);
        customer1.printBill();

        //第二位顾客
        Customer customer2 = new Customer(new NormalStrategy());
        customer2.add(20, 3);
        customer2.add(10, 10);
        customer2.printBill();

        customer2.setStrategy(new FestivalStrategy());
        customer2.add(10, 10);
        customer2.printBill();


    }
}

运行结果:

总共花费: 150.0
总共花费: 230.0
总共花费: 160.0
总共花费: 240.0