什么是策略模式

策略模式(Strategy Pattern):定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换,策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。策略模式是一种对象行为型模式。

策略模式的结构

  • Context:环境类

  • Strategy:抽象策略类

  • ConcreteStrategyA:具体策略类A

  • ConcreteStrategyB:具体策略类B

策略模式的一个实例

一种票(Ticket)有不同的定价策略,如正常(NormalDiscount)状态下原价出售,学生(StudentDiscount)的话就半价优惠。

实例代码

Discount

public abstract class Discount {
    public abstract int calc(int oriPrice);
}

NormalDiscount

public class NormalDiscount extends Discount {
    @Override
    public int calc(int oriPrice) {
        return oriPrice;
    }
}

StudentDiscount

public class StudentDiscount extends Discount {
    @Override
    public int calc(int oriPrice) {
        return (int) (oriPrice * 0.5);
    }
}

Ticket

public class Ticket {
    private Discount discount;
    private int oriPrice;

    public void setOriPrice(int oriPrice) {
        this.oriPrice = oriPrice;
    }

    public void setDiscount(Discount discount) {
        this.discount = discount;
    }

    public int getPrice(){
        return discount.calc(oriPrice);
    }
}

Client

public class Client {
    public static void main(String[] args){
        int currentPrice = 0;
        int oriPrice = 100;

        Ticket ticket = new Ticket();
        ticket.setOriPrice(oriPrice);
        System.out.println("OriPrice : " + oriPrice);

        ticket.setDiscount(new NormalDiscount());
        currentPrice = ticket.getPrice();
        System.out.println("Current Price : " + currentPrice);

        ticket.setDiscount(new StudentDiscount());
        currentPrice = ticket.getPrice();
        System.out.println("Current Price : " + currentPrice);
    }
}

实例结果

OriPrice : 100
Current Price : 100
Current Price : 50

(完)