我与C++设计模式(十三)——策略模式

strategy模式的起因跟template模式是一样的,只不过,它是在template模式上进行了一层改进。我们知道template模式是充分利用了多态的特点,用继承的方式实现了依赖倒转,然而正是继承的强制性约束关系给它带来了不足之处。即,abstract_class的子类中各种原语方法primitive_operation()无法共享,试想,当一个类似于abstract_class的变体abstract_class_2定义了不一样的template_method(),其原语方法想共用前面提到的primitive_operation(),在继承体系中是没法实现的。因为concrete_class跟abstract_class_2没有继承关系。

strategy模式用的是组合,而不是继承,见UML图:


代码:

#ifndef _STRATEGY_H__
#define _STRATEGY_H__

class strategy
{
        public:
                strategy();
                virtual ~strategy();

                virtual void algrithm_interface() = 0;
};

class concrete_strategy_A:public strategy
{
        public:
                concrete_strategy_A();
                ~concrete_strategy_A();
                void algrithm_interface();
};

class concrete_strategy_B:public strategy
{
        public:
                concrete_strategy_B();
                ~concrete_strategy_B();
                void algrithm_interface();
};
#endif
//strategy.cpp
#include "strategy.h"
#include <iostream>
using namespace std;

strategy::strategy()
{
}

strategy::~strategy()
{
}


concrete_strategy_A::concrete_strategy_A()
{
}

concrete_strategy_A::~concrete_strategy_A()
{
}

void concrete_strategy_A::algrithm_interface()
{
        cout<<"A::ALGRITHM_INTERFACE"<<endl;
}


concrete_strategy_B::concrete_strategy_B()
{
}

concrete_strategy_B::~concrete_strategy_B()
{
}

void concrete_strategy_B::algrithm_interface()
{
        cout<<"B::ALGRITHM_INTERFACE"<<endl;
}

#ifndef _CONTEXT_H__
#define _CONTEXT_H__

class strategy;

class context
{
        public:
                context(strategy *);
                ~context();

                void operation();

        private:
                strategy *_p_stg;
};
#endif

//context.cpp

#include "strategy.h"
#include "context.h"
#include <iostream>
using namespace std;

context::context(strategy *p_stg)
        :_p_stg(p_stg)
{
}

context::~context()
{
        if (_p_stg)
                delete _p_stg;
}

void context::operation()
{
        _p_stg->algrithm_interface();
}

#include "strategy.h"
#include "context.h"
#include <iostream>
using namespace std;

int main(int argc,char **argv)
{
        strategy *p_stg = new concrete_strategy_A();
        context *p_con = new context(p_stg);
        p_con->operation();
        if (p_con)
                delete p_con;

        return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值