Decorator mode:
Decorator Pattern dynamically adds some extra responsibilities to an object. In terms of adding object functions, decorator pattern is more flexible than generating subclass implementation.
Transformers in decorator mode example:
From the class diagram, it can be seen that both Changer and Car implement the move interface of transform, and Changer has a transform dependency injection, which is used to point to Car to decorate Car.
This instance and future instances will be in the form of smart pointers, so you don't have to free memory yourself.
Abstract component class Transform:
//Abstract component class Transform class Transform{ public: virtual void move() = 0; };
Specific component Car:
//Specific component Car class Car : public Transform{ public: Car(){ cout << "Transformer is a car!" << endl; } void move(){ cout << "Move on land." << endl; } };
Abstract decoration class:
//Abstract decoration class class Changer : public Transform{ public: Changer(shared_ptr<Transform> transform){ this->transform = transform; } void move(){ transform->move(); } private: shared_ptr<Transform> transform; };
Specific decoration Robot:
//Specific decoration Robot class Robot : public Changer{ public: Robot(shared_ptr<Transform> transform) : Changer(transform){ cout << "Become a robot!" << endl; } void say(){ cout << "speak!" << endl; } };
Specific decoration AirPlane:
//Specific decoration AirPlane class Airplane : public Changer{ public: Airplane(shared_ptr<Transform> transform) : Changer(transform){ cout << "Turning into an airplane!" << endl; } void say(){ cout << "Flying in the sky!" << endl; } };
Client test:
//Client test int main(void){ shared_ptr<Transform> camaro = make_shared<Car>(); camaro->move(); cout << "--------------" << endl; shared_ptr<Robot> bumblebee = make_shared<Robot>(camaro); bumblebee->move(); bumblebee->say(); return 0; }
Output:
(End)