标签:
1 // Decorator.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <memory> 6 #include <string> 7 #include <iostream> 8 using namespace std; 9 10 class Person 11 { 12 public: 13 Person(string name = ""): name_(name) 14 {} 15 virtual void Show() 16 { 17 cout << "My name is :" << name_ << endl; 18 } 19 protected: 20 string name_; 21 }; 22 23 class Finery : public Person 24 { 25 public: 26 void Decorator(shared_ptr<Person> person) 27 { 28 person_ = person; 29 } 30 virtual void Show() 31 { 32 if (nullptr != person_) 33 { 34 person_->Show(); 35 } 36 } 37 protected: 38 shared_ptr<Person> person_; 39 }; 40 41 class TShirt :public Finery 42 { 43 public: 44 virtual void Show() 45 { 46 cout << "This is TShirt." << endl; 47 person_->Show(); 48 } 49 }; 50 51 class Sneaker : public Finery 52 { 53 public: 54 virtual void Show() 55 { 56 cout << "This is Sneaker." << endl; 57 person_->Show(); 58 } 59 }; 60 61 int main() 62 { 63 auto person = make_shared<Person>("cauchy"); 64 auto tshirt = make_shared<TShirt>(); 65 auto sneaker = make_shared<Sneaker>(); 66 tshirt->Decorator(person); 67 tshirt->Show(); 68 sneaker->Decorator(tshirt); 69 sneaker->Show(); 70 71 return 0; 72 }
标签:
原文地址:http://www.cnblogs.com/cauchy007/p/5331073.html