Java设计模式(3) -- 策略

Strategy

 

英文简单描述

Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm change dynamically.


How to
Strategy
declares an interface common to all supported algorithms.
ConcreteStrategy
implements the algorithm using the Strategy interface.
Context
is configured with a ConcreteStrategy object.
maintains a reference to a Strategy object.
may define an interface that lets Strategy access its data.

Known cases
Linebreak
Encrypt Algorithm

UML

Java设计模式(3) -- 策略_第1张图片

 

代码实现:

public interface IStrategy { double compute(Context context); } public class ConcreteStrategyA implements IStrategy { public double compute(Context context) { return context.getValue(); } } public class ConcreteStrategyB implements IStrategy { public double compute(Context context) { return context.getValue() * 0.5; } } public class Context { private IStrategy strategy; public void setStrategy(IStrategy strategy) { this.strategy = strategy; } public Context() {} public double getValue() { return 3.0; } public void compute() { double val = strategy.compute(this); System.out.println("Value=" + val); } } public class TestStrategy { public static void main(String[] args) { IStrategy strategy = null; //根据配置生成相应的策略 strategy = new ConcreteStrategyB(); Context context = new Context(); context.setStrategy(strategy); context.compute(); } }

 

委托和继承:

策略是通过另一个层次结构IStrategy来实现不同算法的,Context将compute委托给策略类

也可以用另一种方法来实现Context的compute的多样化:即继承Context,对于不同的compute提供不同的子类

这就涉及到委托和继承的选择问题

委托比继承灵活,可以动态配置,不会造成子类级数增长,另外可以通过对象的合成来实现多种功能(Decorator)

继承则相对不灵活,一旦选择了子类后,不能动态配置

另外,委托是黑盒重用,继承是白盒重用,应该多使用委托少用继承

你可能感兴趣的:(Java设计模式(3) -- 策略)