策略模式(Strategy Pattern)

来源:互联网 发布:无法连接至steam网络 编辑:程序博客网 时间:2024/06/11 03:43

策略模式(Strategy Pattern)定义了算法家族,分别封装起来,他们之间可以相互替换,此模式可以让算法的变化不会影响到使用这些算法的客户端。

目的:定义一系列的算法,把它们封装起来,使用的时候达到互相替换的目的。

使用策略模式主要解决了在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护的问题。

在策略模式中一般用创建一个Context(上下文)类,用于维护一个Strategy引用。

Strategy UML图


Java实现:

Strategy.java(策略类接口)

/* *Strategy Interface */public interface Strategy{void algorithmInterface();}
StrategyA.java(策略A)
public class StrategyA implements Strategy{public void algorithmInterface(){System.out.println("Strategy A");}}
StrategyB.java(策略B)
public class StrategyB implements Strategy{public void algorithmInterface(){System.out.println("Strategy B");}}
StrategyC.java(策略C)
public class StrategyC implements Strategy{public void algorithmInterface(){System.out.println("Strategy C");}}
Context.java(用于维护一个Strategy的引用)
public class Context{private Strategy s;public Context(Strategy s){this.s = s;}public void contextInterface(){s.algorithmInterface();}}
Test.java(测试)

public class Test{public static void main(String []args){Context contextA = new Context(new StrategyA());contextA.contextInterface();Context contextB = new Context(new StrategyB());contextB.contextInterface();Context contextC = new Context(new StrategyC());contextC.contextInterface();}}


C++实现:

strategy.h(抽象类)

#ifndef STRATEGY_H_#define STRATEGY_H_//策略 抽象类 #include <iostream>class Strategy{public:virtual void algorithmInterface() = 0;virtual ~Strategy(){ }};#endif
strategyA.h(策略A)

#ifndef STRATEGYA_H_#define STRATEGYA_H_#include "strategy.h"using std::cout;using std::endl;//策略A class StrategyA:public Strategy{public:void algorithmInterface (){cout<<"Strategy A"<<endl;}};#endif
strategyB.h(策略B)

#ifndef STRATEGYB_H_#define STRATEGYB_H_#include "strategy.h"using std::cout;using std::endl;//策略B class StrategyB:public Strategy{public:void algorithmInterface (){cout<<"Strategy B"<<endl;}};#endif

strategyC.h(策略C)

#ifndef STRATEGYC_H_#define STRATEGYC_H_#include "strategy.h"using std::cout;using std::endl;//策略C class StrategyC:public Strategy{public:void algorithmInterface (){cout<<"Strategy C"<<endl;}};#endif
context.h(上下文)
#ifndef CONTEXT_H_#define CONTEXT_H_#include "strategy.h"//上下文,负责根据具体的策略,调用具体的算法。 class Context{private:Strategy *s;public:Context(Strategy *s){this->s = s;}Context(){this->s = nullptr; }void contextInterface(){s->algorithmInterface();}virtual ~Context(){ delete s;}};#endif
main.cpp(测试)
#include "strategy.h"#include "strategyA.h"#include "strategyB.h"#include "strategyC.h"#include "context.h"int main(){/*Strategy* s = new StrategyA();s->algorithmInterface();*/Context *cA = new Context(new StrategyA());cA->contextInterface(); Context *cB = new Context(new StrategyB());cB->contextInterface(); Context *cC = new Context(new StrategyC());cC->contextInterface(); delete cA;delete cB,cC;return 0;} 



0 0