Decorator pattern in C++

▼魔方 西西 提交于 2019-12-28 04:08:31

问题


Can someone give me an example of the Decorator design pattern in C++ ? I have come across the Java version of it, but found it difficult to understand the C++ version of it (from the examples I found).

Thanks.


回答1:


Vince Huston Design Patterns, even though its layout is poor, has C++ implementation for most design patterns in the Gang of Four book.

Click for Decorator.

There isn't much difference with Java, except the manual memory handling that you'd better wrap with smart pointers :)




回答2:


I've found the website Sourcemaking to be a pretty good one when it comes to explaining different Design Patterns.

The Decorator design pattern has C++ examples, such as an overview example, a "before and after", and an example with packet encoding/decoding.




回答3:


#include <iostream>
using namespace std;

class Computer
{
public:
    virtual void display()
    {
        cout << "I am a computer..." << endl;
    }
};

class CDDrive : public Computer
{
private:
    Computer* c;
public:
    CDDrive(Computer* _c)
    {
        c = _c;
    }
    void display()
    {
        c->display();
        cout << "with a CD Drive..." << endl;
    }
};

class Printer : public Computer
{
private:
    CDDrive* d;
public:
    Printer(CDDrive* _d)
    {
        d = _d;
    }
    void display()
    {
        d->display();
        cout << "with a printer..." << endl;
    }
};

int main()
{
    Computer* c = new Computer();
    CDDrive* d = new CDDrive(c);
    Printer* p = new Printer(d);

    p->display();
}


来源:https://stackoverflow.com/questions/2988066/decorator-pattern-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!