第三周介紹了繼承多態(tài),然后利用一些設(shè)計方法說明了封裝。一來考慮到后續(xù)的課程《設(shè)計模式》,二來此時的理解還很粗糙泌射,暫且壓下燥爷。需要補(bǔ)充的要點(diǎn):1.復(fù)合于委托妈踊;2.原型設(shè)計;3.Method template
1.關(guān)于委托#
委托是對一個類的功能進(jìn)行擴(kuò)展和復(fù)用的方法寺擂。它的做法是:寫一個附加的類提供附加的功能球涛,并使用原來的類的實(shí)例提供原有的功能
從某種意義上來說,它和繼承相似亡脸,都可以使用其他的類的功能。不過不同的树酪,繼承往往必須在邏輯上存在固定的關(guān)系浅碾,不如委托靈活。
委托是一種模式续语,委托者不完成實(shí)際的工作垂谢,也不關(guān)心完成工作的細(xì)節(jié),但有完成工作的接口疮茄,這個接口只是將請求發(fā)給被委托者來完成滥朱。下面用一個最基本的例子來說明這個問題:
Demo_01
//MyString 是委托類,String是被委托類
class MyString
{
public:
MyString();
~MyString();
void MyInsert(char ch,int pos);
public:
void MyUniqFun(void);
private:
String *m_pstr;
};
MyString::MyString()
{
m_pstr=new String;
}
MyString::~MyString()
{
delete m_pstr;
}
void MyString::MyInsert(char ch,int pos)
{
m_pstr->insert(ch,pos); //委托力试,把插入功能委托給String實(shí)現(xiàn)徙邻,MyString只提供接口
}
void MyUniqFun(void)
{
//此處可自由發(fā)揮,實(shí)現(xiàn)該類的獨(dú)特功能
}
2.關(guān)于原型
原型模式:用原型實(shí)例指定創(chuàng)建對象的種類畸裳,并且通過拷貝這些原型創(chuàng)建新的對象缰犁。
創(chuàng)建一個原型的虛基類,聲明一個拷貝自身的接口怖糊,然后根據(jù)子類的具體原型類帅容,利用拷貝構(gòu)造函數(shù)實(shí)現(xiàn)自身的拷貝操作。
下面是源于《大話設(shè)計模式》書中一份代碼說明:
Demo_02
#include <cstdio>
//接口
class CPrototype
{
public:
CPrototype(){}
virtual ~CPrototype(){}
virtual CPrototype* Clone() = 0;
};
//實(shí)現(xiàn)
class CConcretePrototype : public CPrototype
{
public:
CConcretePrototype():m_counter(0){}
virtual ~CConcretePrototype(){}
//拷貝構(gòu)造函數(shù)
CConcretePrototype(const CConcretePrototype& rhs)
{
m_counter = rhs.m_counter;
}
//復(fù)制自身
virtual CPrototype* Clone()
{
//調(diào)用拷貝構(gòu)造函數(shù)
return new CConcretePrototype(*this);
}
private:
int m_counter;
};
int main(int argc, char **argv)
{
//生成對像
CPrototype* conProA = new CConcretePrototype();
//復(fù)制自身
CPrototype* conProB = conProA->Clone();
delete conProA; conProA=NULL;
delete conProB; conProB=NULL;
return 0;
}