简介:
策略模式的意图是定义一系列算法,把它们一个个封装起来,并且使它们可互相替换。该模式使得算法可独立于使用它的客户而变化。
在有多种算法相似的情况下,使用 if...else 会带来复杂和难以维护。
介绍:
![](https://i-blog.csdnimg.cn/blog_migrate/3e93b184222f8950dc83b4437e78e5bc.png)
优点 | 1.易于扩展,新增具体策略类即可。 2.避免使用条件选择语句。 3.由于环境角色内有公共策略接口,方便切换。 |
缺点 | 1.策略类全部需要暴露给客户端。 2.可能会有很多的具体策略类。 |
特点 | 1.消除条件判断语句,就是在解耦合。 |
环境角色(Context) | 持有一个Strategy类的引用。需要使用ConcreteStrategy提供的算法。 内部维护一个Strategy的实例。负责动态设置运行时Strategy具体的实现算法。负责跟Strategy之间的交互和数据传递 |
抽象策略角色(Strategy) | 抽象公共接口。 |
具体策略角色(ConcreteStrategy) | 实现接口,提供具体的算法。 |
模板模式:执行算法的步骤协议是本身放在抽象类里面的,允许一个通用的算法操作多个可能实现。
策略模式:执行算法的协议是在具体类,每个具体实现有不同通用算法来做。
使用:
//Context
public sealed class ShapeArea
{
private IShape _shape;
public IShape _IShape
{
get { return _shape; }
set { _shape = value; }
}
public ShapeArea(IShape shape)
{
_shape = shape;
}
public double GetArea()
{
return _shape.Area();
}
}
//Strategy
public interface IShape
{
double Area();
}
//ConcreteStrategyA
public sealed class Square : IShape
{
private double x;
public Square(double d)
{
x = d;
}
public double Area()
{
return x * x;
}
}
//ConcreteStrategyB
public sealed class Circle : IShape
{
private double r;
public Circle(double d)
{
r = d;
}
public double Area()
{
return Math.PI * r * r;
}
}
//策略模式调用
ShapeArea shapeArea = new ShapeArea(new Square(1));
double d = shapeArea.GetArea();
shapeArea._IShape = new Circle(1);
d = shapeArea.GetArea();