常見設(shè)計模式的解析和實(shí)現(xiàn)(C++)之十六-Strategy模式
作用:
定義一系列的算法,把它們一個個封裝起來, 并且使它們可相互替換.本模式使得算法可獨(dú)立于使用它的客戶而變化.
UML結(jié)構(gòu)圖:

解析:
簡而言之一句話,Strategy模式是對算法的封裝.處理一個問題的時候可能有多種算法,這些算法的接口(輸入?yún)?shù),輸出參數(shù)等)都是一致的,那么可以考慮采用Strategy模式對這些算法進(jìn)行封裝,在基類中定義一個函數(shù)接口就可以了.
實(shí)現(xiàn):
1)Strategy.h

/**//********************************************************************
????created:????2006/08/06
????filename:?????Strategy.h
????author:????????李創(chuàng)
????????????????http://www.shnenglu.com/converse/

????purpose:????Strategy模式的演示代碼
*********************************************************************/

#ifndef?STRATEGY_H
#define?STRATEGY_H

class?Strategy;

class?Context


{
public:
????Context(Strategy?*pStrategy);
????~Context();

????void?ContextInterface();
private:
????Strategy*?m_pStrategy;
};

class?Strategy


{
public:

????virtual?~Strategy()
{}

????virtual?void?AlgorithmInterface()?=?0;
};

class?ConcreateStrategyA
????:?public?Strategy


{
public:

????virtual?~ConcreateStrategyA()
{}

????virtual?void?AlgorithmInterface();
};

#endif

2)Strategy.cpp

/**//********************************************************************
????created:????2006/08/06
????filename:?????Strategy.cpp
????author:????????李創(chuàng)
????????????????http://www.shnenglu.com/converse/

????purpose:????Strategy模式的演示代碼
*********************************************************************/

#include?<iostream>
#include?"Strategy.h"

Context::Context(Strategy?*pStrategy)
????:?m_pStrategy(pStrategy)


{
}

Context::~Context()


{
????delete?m_pStrategy;
????m_pStrategy?=?NULL;
}

void?Context::ContextInterface()


{
????if?(NULL?!=?m_pStrategy)

????
{
????????m_pStrategy->AlgorithmInterface();
????}
}

void?ConcreateStrategyA::AlgorithmInterface()


{
????std::cout?<<?"AlgorithmInterface?Implemented?by?ConcreateStrategyA\n";
}

3)Main.cpp

/**//********************************************************************
????created:????2006/08/06
????filename:?????Main.cpp
????author:????????李創(chuàng)
????????????????http://www.shnenglu.com/converse/

????purpose:????Strategy模式的測試代碼
*********************************************************************/

#include?"Strategy.h"

int?main()


{
????Strategy*?pStrategy?=?new?ConcreateStrategyA();
????Context*??pContext??=?new?Context(pStrategy);

????pContext->ContextInterface();

????delete?pContext;

????return?0;
}
定義一系列的算法,把它們一個個封裝起來, 并且使它們可相互替換.本模式使得算法可獨(dú)立于使用它的客戶而變化.
UML結(jié)構(gòu)圖:

解析:
簡而言之一句話,Strategy模式是對算法的封裝.處理一個問題的時候可能有多種算法,這些算法的接口(輸入?yún)?shù),輸出參數(shù)等)都是一致的,那么可以考慮采用Strategy模式對這些算法進(jìn)行封裝,在基類中定義一個函數(shù)接口就可以了.
實(shí)現(xiàn):
1)Strategy.h























































2)Strategy.cpp















































3)Main.cpp


























posted on 2006-08-06 22:22 那誰 閱讀(2817) 評論(1) 編輯 收藏 引用 所屬分類: 設(shè)計模式