设计模式3:策略模式

策略模式是一种行为模式。一般跟算法有关,跟实现无关的一种模式,策略模式的作用,通常事为了解决同一个问题的多种不同方法。例如:从A城市到B城市,可以有多种出行方式,每种出行方式可以有不同的步骤和交通方式,因为维护每种出行方式很繁琐,所以策略模式下,提供一种“按需分配”的交通方式,就好比导航一样,提供给用户一种用户接受的方式,但是用户并不需要知道导航内部是如何实现这一的算法的。再比如java中的算法包也是如此,在Context中传入某个算法的名称,就可以调用对应的算法的功能,但是context并不实现算法,而是在具体的算法类中实现。

策略模式有这么几个步骤:

1)声明一个策略的抽象接口

2)通过策略的接口,实现多个具体的策略

3)定义一个上下文选择某种策略

4)具体的策略返回响应的结果

策略模式,实际上是C++的封装和多态的应用。

---------------C++描述-----------------

class IStrategy

{

public:

virtual Type execute(Type 1, Type b) = 0;

};

class SubstractStrategy:public IStrategy

{

public:

virtual Type execute(Type a, Type b)

{

return a - b;

}

};

class AddtionStrategy:public IStrategy

{

public:

virtual Type execute(Type a, Type b)

{

return a + b;

}

};

class StrategyContext

{

public:

void SetStrategy(IStrategy* pStrategy)

{

m_pStrategy = pStrategy;

}

Type execute(Type a, Type b)

{

return strategy.execute(a, b);

}

private:

IStrategy* m_pStrategy;

};

client.cpp

int main(int argc, char **argv)

{

StrategyContext *ctx = new StrategyContext;

AddtionStrategy *pAddStrategy = new AddtionStrategy;

ctx->SetStrategy(pAddStrategy );

ctx->execute(1,2);

SubstractStrategy *pSubStrategy = new SubstractStrategy;

ctx->SetStrategy(pSubStrategy);

ctx->execute(1,2);

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。