今天看到裝飾者模式,中間提到了建造者模式,雖然還沒看過建造者模式,但是想想看就應該知道二者的區別:
前者是對象的組成是不固定的,比如一個person,想穿幾件clothes都可以,而建造者模式,就是所有的組成都必須是確定的,就好像某個型號的電腦,必須包含主板、顯卡、記憶體……
具體的應用還不太清晰。
但是原理基本上是這樣的:一個【基類Component】,提供統一的介面,子類主要分為【裝飾類DecoratorComponent】和【被裝飾類PersonComponent】
【DecoratorComponent】又可以派生子類【TShirtsDecoratorComponent】、【TrouserDecoratorComponent】……
用以裝飾PersonComponent類。
【基類Component】
//基類class Component{public: Component(void); virtual ~Component(void); virtual void CommonInterface(void) const = 0;};Component::Component(void){ }Component::~Component(void){ }
【被裝飾類PersonComponent】
//被裝飾類class PersonComponent : public Component{public: PersonComponent(void); ~PersonComponent(void); virtual void CommonInterface(void) const;};PersonComponent::PersonComponent(void){ }PersonComponent::~PersonComponent(void){ }void PersonComponent::CommonInterface(void) const{ std::cout << "被裝飾者 小菜\n";}
【裝飾類DecoratorComponent】
//裝飾類class DecoratorComponent : public Component{public: DecoratorComponent(void); virtual ~DecoratorComponent(void); virtual void CommonInterface(void) const; void setComponent(Component* comp);protected: Component* component;};DecoratorComponent::DecoratorComponent(void){ }DecoratorComponent::~DecoratorComponent(void){ }void DecoratorComponent::CommonInterface(void) const{ if (this->component != NULL) { component->CommonInterface(); }}void DecoratorComponent::setComponent(Component* comp){ this->component = comp;}
【裝飾子類TShirtsDecoratorComponent】
//裝飾子類TShirtsDecoratorComponentclass TShirtsDecoratorComponent : public DecoratorComponent{public: TShirtsDecoratorComponent(void); virtual ~TShirtsDecoratorComponent(void); virtual void CommonInterface(void) const;};TShirtsDecoratorComponent::TShirtsDecoratorComponent(void){ }TShirtsDecoratorComponent::~TShirtsDecoratorComponent(void){ }void TShirtsDecoratorComponent::CommonInterface(void) const{ DecoratorComponent::CommonInterface(); std::cout << "TShirts Decorated!\n";}
【裝飾子類TrouserDecoratorComponent】
//裝飾子類TrouserDecoratorComponentclass TrouserDecoratorComponent : public DecoratorComponent{public: TrouserDecoratorComponent(void); virtual ~TrouserDecoratorComponent(void); virtual void CommonInterface(void) const;};TrouserDecoratorComponent::TrouserDecoratorComponent(void){ }TrouserDecoratorComponent::~TrouserDecoratorComponent(void){ }void TrouserDecoratorComponent::CommonInterface(void) const{ DecoratorComponent::CommonInterface(); std::cout << "Trouser Decorated!\n";}
【main】
int main(int argc, const char * argv[]){ PersonComponent* person = new PersonComponent(); TShirtsDecoratorComponent* tShirts = new TShirtsDecoratorComponent(); TrouserDecoratorComponent* trouser = new TrouserDecoratorComponent(); tShirts->setComponent(person); trouser->setComponent(tShirts); trouser->CommonInterface(); delete trouser; trouser = NULL; delete tShirts; tShirts = NULL; delete person; person = NULL; return 0;}
【結果】
被裝飾者 小菜
TShirts Decorated!
Trouser Decorated!