一、對象模式所屬類別簡介-組件協作模式
組件模式通過晚綁定來實現鬆耦合(virtual)
組件協作模式包含以下三種:
TemplateMethod
Observer(event)
strategy
二、當前模式簡介-TemplateMethod
TemplateMethod
三、需求
有五個步驟,dll庫編寫者寫135步驟,應用層編寫者寫24步驟。
四、設計一
#include <iostream>
using namespace std;
class Library
{
public:
void step1(){ std::cout << "step1" << std::endl;}
void step3(){ std::cout << "step3" << std::endl;}
void step5(){ std::cout << "step5" << std::endl;}
};
class Application
{
public:
void step2(){ std::cout << "step2" << std::endl;}
void step4(){ std::cout << "step4" << std::endl;}
};
int main()
{
Application application;
Library library;
library.step1();
application.step2();
library.step3();
application.step4();
library.step5();
return 0;
}
//打印
step1
step2
step3
step4
step5
五、需求更改
無
六、設計一更改版本
無
七、違反原則
1.違反重構b 早綁定,main裏面在編譯的時候就要把1-5個步驟綁定起來,使用虛函數是可以實現運行時再綁定。
八、設計二
#include <iostream>
using namespace std;
class Library
{
public:
virtual ~Library() {};
void run() //穩定骨架
{
step1();
step2();
step3();
step4();
step5();
}
protected:
void step1(){ std::cout << "step1" << std::endl;} //穩定(普通函數)
void step3(){ std::cout << "step3" << std::endl;} //穩定(普通函數)
void step5(){ std::cout << "step5" << std::endl;} //穩定(普通函數)
virtual void step2() = 0; //變化(使用虛函數)
virtual void step4() = 0; //變化(使用虛函數)
};
class Application : public Library
{
public:
~Application() {};
protected:
void step2(){ std::cout << "step2" << std::endl;}
void step4(){ std::cout << "step4" << std::endl;}
};
int main()
{
Library *library = new Application();
library->run();
return 0;
}
//打印
step1
step2
step3
step4
step5
九、設計二更改版本
無
十、設計二比設計一區別
1.一個使用了虛函數,延遲綁定
十一、模式定義
先定義一個骨架(穩定的主流程),子步驟留到子類實現。
十二、模式結構
十三、要點總結
穩定-不寫成虛函數,不穩定-寫成虛函數
run(骨架)要穩定
不要調用我,我調用你,反向控制——晚綁定
沒有用的不要public出來,統一protected(比如子類的變化步驟)
幾乎有用到虛函數,就是template模式