设计模式之策略模式

⭐   ​策略模式定义了算法家族,分别封装起来,让他们之间可以互相替换。策略模式让算法独立于使用它的客户而独立变化,即算法的变化,不会影响到使用算法的客户。

个人理解,通俗来讲就是策略模式的点在于封装变化。举个例子,画家画画,他能画国画、蜡笔画、油画等等,画各种风格的画用的画笔不一样、颜料不一样……那这些不同方式的画画其实就是变化的算法(策略)。如果将实现这些画画的代码都集成在画家类中,日后一旦任何一种画画方式发生改变就需要去修改画家类,就违反开放-封闭原则。

 

代码如下(偷懒了,类没有加构造和析构)

#include <iostream>

#include <string>

using namespace std;

 

 

class BrushStrategy

{

public:

    virtual void Paint() = 0;

};

 

class Pastel :public BrushStrategy

{

public:

    virtual void Paint()

    {

        std::cout << "paint with pastel" << endl;

    }

};

 

class ChinesePen :public BrushStrategy

{

public:

    virtual void Paint()

    {

        std::cout << "paint with chinese-pen" << endl;

    }

};

 

class Painter

{

public:

    void Paint()

    {

        m_brush->Paint();

    }

    void SetBrush(BrushStrategy *i_Brush)

    {

        m_brush = i_Brush;

    }

 

private:

    BrushStrategy *m_brush;

 

};

 

class BrushFactory

{

public:

    BrushStrategy *CreateBrush(int nType)

    {

        BrushStrategy *brush = NULL;

        switch (nType)

        {

        case 1:

            brush = new ChinesePen;

            break;

        case 2:

        default:

            brush = new Pastel;

            break;

        }

        return brush;

    }

 

};

 

int main()

{

    Painter painter;

    BrushFactory bfc;

    BrushStrategy *chinese_pen = bfc.CreateBrush(1);

    painter.SetBrush(chinese_pen);

    painter.Paint();

    delete chinese_pen;

    chinese_pen = NULL;

 

    BrushStrategy *pastel = bfc.CreateBrush(2);

    painter.SetBrush(pastel);

    painter.Paint();

    delete pastel;

    pastel = NULL;

 

    return 1;

}

结果如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值