行为模式--策略模式

视频连接:https://www.bilibili.com/video/BV1iQ4y1M7FV/

今天由为大家介绍一下策略模式,

先给大家提出一个问题,假设现在是国企假期,我们要去外地旅游,需要选择一种出游方式,可以骑自行车,坐汽车,坐火车,坐飞机,都可以达到我们的目的,请问我们如何进行选择。

如何进行这个选择,由此引出我们策略模式的模式动机

 

而模式策略的定义又是什么呢?

如果我们不适用策略模式,我们将这样来选择出行方式

这中写法造成如果我们要增加或者删除方法都需要修改整个Context中的algorithm(),不利于我们动态灵活的选择算法已达到出行的目的

代码:

public class Context
{    ……
    public void algorithm(String type)  
    {
        ......
        if(type == "strategyA")
        {
            //A方法
        }
        else if(type == "strategyB")
        {
            //B方法
        }
        else if(type == "strategyC")
        {
            //C方法
        }
        ......
    }
    ……
} 

如果我们使用了策略模式,重构这次出行的选择,

首先画出策略模式的结构:

根据类图写出代码

 代码

public abstract class AbstractStrategy
{
    public abstract void algorithm();  
} 
public class ConcreteStrategyA extends AbstractStrategy
{
    public void algorithm()
    {
        //算法A
    }
} 
public class Context
{
    private AbstractStrategy strategy;
    public void setStrategy(AbstractStrategy strategy)
    {
        this.strategy= strategy;
    }
    public void algorithm()
    {
        strategy.algorithm();
    }
} 


Context context = new Context();
AbstractStrategy strategy;
strategy = new ConcreteStrategyA();
context.setStrategy(strategy);
context.algorithm();

由此见得,一个系统需要动态地在几种算法中选择一种时,使用策略模式是个好的选择

原文地址:https://www.cnblogs.com/LiaoMengyu/p/12823717.html