C++中的装饰器模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2988066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:42:27  来源:igfitidea点击:

Decorator pattern in C++

c++design-patternsdecorator

提问by AlgoMan

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).

有人可以给我一个 C++ 装饰器设计模式的例子吗?我遇到过它的 Java 版本,但发现很难理解它的 C++ 版本(从我发现的例子中)。

Thanks.

谢谢。

采纳答案by Matthieu M.

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

Vince Huston Design Patterns,尽管它的布局很差,但在四人组书中的大多数设计模式都有 C++ 实现。

Click for Decorator.

点击装饰器

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

与 Java 没有太大区别,除了您最好用智能指针包装的手动内存处理:)

回答by Dan

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

解释不同的设计模式时,我发现Sourcemaking网站是一个很好的网站。

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

装饰设计图案具有C ++的例子,如一个综合性实例中,“前后”,以及与数据包编码示例/解码

回答by Rajeev

#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();
}