using namespace std;
//装饰器模式(分三种:
// 1.装饰类继承被装饰类
// 2.装饰类将被装饰类作为自己的属性
// 3.装饰类与被装饰类有共同父类**
//1.装饰类继承被装饰类
class Person {
protected:
string m_name;
public:
Person(string name) :m_name(name) {}
virtual void show() = 0;
};
class Man :public Person {
public:
Man(string name) :Person(name) {}
virtual void show() {
cout << “男孩” << m_name;
}
};
class ExtendDecorative:public Person {
public:
ExtendDecorative(string name):Person(name) {}
virtual void addClothes() {
cout << m_name << “穿上了衣服” << endl;
}
virtual void necklacing() {
cout << m_name << “戴上了项链” << endl;
}
virtual void show() {
addClothes();
necklacing();
}
};
void testExtendDecorative() {
shared_ptr<ExtendDecorative
> extendDecorative{new ExtendDecorative(“huahua”) };
extendDecorative->show();
}
//2.装饰类将被装饰类作为自己的属性
class Car {
public:
virtual void show() = 0;
};
class Audi :public Car {
void show() {
cout << “这是一辆奥迪车”;
}
};
//装饰层
class Decorative{
protected:
shared_ptr<Car
> m_car;
public:
Decorative(shared_ptr<Car
> car):m_car(car){}
void show() {
m_car->show();
//加装饰
cout << “,可以弹射漂移” << endl;
}
};
//测试被装饰类作为属性
void testDecorative() {
shared_ptr<Car
>car{ new Audi() };
shared_ptr<Decorative
> decorative{ new Decorative(car) };
decorative->show();
}
//3.装饰类与被装饰类有共同父类(现在给的例子两个子类没有任何联系)
class Transfer {
public:
virtual void answer() = 0;
virtual void sweep() {}
virtual void TakeOutTheGarbage() {}
};
//被装饰类
class Robot :public Transfer {
public:
virtual void answer() {
cout << “Robot回答问题” << endl;
}
virtual void sweep() {
cout << “扫地” << endl;
}
};
//装饰类
class CommonParentDecorative :public Transfer {
private:
shared_ptr<Transfer
>m_transfer;
public:
CommonParentDecorative(shared_ptr<Transfer
> transfer):m_transfer(transfer) {}
virtual void answer() {
cout << “CommonParentDecorative回答问题” << endl;
}
virtual void TakeOutTheGarbage() {
cout << “CommonParentDecorative倒垃圾” << endl;
}
};
//测试装饰类与被装饰类有共同父类
void testCommonParentDecorative() {
shared_ptr<Transfer
>transfer{ new Robot };
transfer->answer();
transfer->sweep();
shared_ptr<Transfer
>transfer1{ new CommonParentDecorative(transfer) };
transfer1->answer();
transfer1->TakeOutTheGarbage();
}
int main() {
//1.测试装饰类继承被装饰类
/testExtendDecorative();/
//2.装饰类将被装饰类作为自己的属性
testDecorative();
//3.测试装饰类与被装饰类有共同父类
/testCommonParentDecorative();/
return 0;
}
不好意思,脑子里想不到例子了,望谅解,大家凑合看看,谢谢
c++设计模式-装饰器模式(1.装饰类继承被装饰类;2.装饰类将被装饰类作为自己的属性;3.装饰类与被装饰类有共同父类)
于 2023-11-18 19:18:04 首次发布