“策略模式”:__定义了一系列的算法并提供运行时动态更改算法的能力,保证了客户端代码的简洁性__。
实现方式:
创建__策略接口__;
创建多个__策略类__继承__策略接口__并通过不同算法实现接口中声明的方法;
创建一个__消费者类__,它必须存储一个__策略对象__的引用并对外提供一个可修改该引用的方法;
在执行环境的上下文通过动态的更改__消费者对象__中存储的__策略对象__引用来达到动态更改算法的目的;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 import java.util.ArrayList;import java.util.List;public class StrategyPatternWiki { public static void main (final String[] arguments) { Customer firstCustomer = new Customer(new NormalStrategy()); firstCustomer.add(1.0 , 1 ); firstCustomer.setStrategy(new HappyHourStrategy()); firstCustomer.add(1.0 , 2 ); Customer secondCustomer = new Customer(new HappyHourStrategy()); secondCustomer.add(0.8 , 1 ); firstCustomer.printBill(); secondCustomer.setStrategy(new NormalStrategy()); secondCustomer.add(1.3 , 2 ); secondCustomer.add(2.5 , 1 ); secondCustomer.printBill(); } } class Customer { private List<Double> drinks; private BillingStrategy strategy; public Customer (final BillingStrategy strategy) { this .drinks = new ArrayList<Double>(); this .strategy = strategy; } public void add (final double price, final int quantity) { drinks.add(strategy.getActPrice(price*quantity)); } public void printBill () { double sum = 0 ; for (Double i : drinks) { sum += i; } System.out.println("Total due: " + sum); drinks.clear(); } public void setStrategy (final BillingStrategy strategy) { this .strategy = strategy; } } interface BillingStrategy { double getActPrice (final double rawPrice) ; } class NormalStrategy implements BillingStrategy { @Override public double getActPrice (final double rawPrice) { return rawPrice; } } class HappyHourStrategy implements BillingStrategy { @Override public double getActPrice (final double rawPrice) { return rawPrice*0.5 ; } }