前言
這是改造前一篇 設計模式 的基礎,使通知者不必知道觀察者的類名和函數名,只需要知道更新函數的原型即可。
開發環境:WIN7 32位 + VS2010
發現在VS2005中使用std::funtion報錯:
錯誤 1 error C2039: “function”: 不是“std”的成員 e:\vsprojectsforvms\designpattern\observer2\observer2.cpp 123
於是改為VS2010來寫。
#include "stdafx.h" //std::function需要此頭文件 #include <functional> #include <vector> #include <iostream> //std::find需要此頭文件 #include <algorithm> using namespace std; /******************************************** First類和Second相當於兩個觀察者, 他們兩個沒有繼承結構 First類和Second類的更新函數原型相同,函數名不必相同 ********************************************/ class First { public: int Add1(int a, int b) //更新函數 { return a + b; } }; class Second { public: int Add2(int a, int b) //更新函數, { return a + b; } }; class CTest { public: typedef std::tr1::function<int(int, int)> PAdd; /*Attach函數來增加觀察者的更新函數 由於std::function沒有重載operator ==, 因此不能用std::find函數, 也不能在Remove中使用*ter == pAdd這樣的比較。 */ void Attach(PAdd pAdd) { // if (std::find(m_vecPtr.begin(), m_vecPtr.end(), pAdd) == m_vecPtr.end()) { m_vecPtr.push_back(pAdd); } } void Remove(PAdd pAdd) { //試圖刪除觀察者的更新函數,報錯 /*for (vector<PAdd>::iterator iter = m_vecPtr.begin(); iter != m_vecPtr.end(); ++ iter) { if (*iter == pAdd) { m_vecPtr.erase(iter); return; } }*/ } void Notify() { for (vector<PAdd>::const_iterator iter = m_vecPtr.begin(); iter != m_vecPtr.end(); ++ iter) { int sum = (*iter)(10, 20); cout<<"result is "<<sum<<endl; } } protected: vector<PAdd> m_vecPtr; }; int _tmain(int argc, _TCHAR* argv[]) { First objFirst; Second objSecond; CSubject obj;
//需要說明的是:std::bind函數的第三第四個參數表示參數的占位符,即對應的Add函數有N個參數,
//這里就有std::placeholders::_1,std::placeholders::_2, ... std::placeholders::_N
CSubject::PAdd pAdd1 = std::bind(&First::Add1, &objFirst, std::placeholders::_1, std::placeholders::_2);
CSubject::PAdd pAdd2 = std::bind(&Second::Add2, &objSecond, std::placeholders::_1, std::placeholders::_2);
obj.Attach(pAdd1); obj.Attach(pAdd2); obj.Notify(); return 0;
}
執行結果:
至於怎么樣讓程序在調用(*iter)時傳入不同的參數,可以修改一下Attach函數,改為類似
void Attach(PAdd, int, int)這樣的形式,讓函數指針和兩個參數一一對應,再調用AddX函數時去查找該函數對應的兩個參數,然后傳給(*iter)(參數1, 參數1)。