c++ - A 类的对象作为 B 类的成员。B 需要 A 的对象来初始化自身

标签 c++ design-patterns

RequestStreamer 只是想帮助 Request 进行流式传输。有没有比您在下面看到的更好的方法来实现它?

这种代码适合什么设计模式?它是所有者模式还是助手模式?

这个例子有助于展示A和B之间的关系。

class Request {
    RequestStreamer* streamer;
    int contentLen;

public:
    Request()
    {
        contentLen = 0;
        streamer = new RequestStreamer(this);
    }
    ~Request()
    {
        delete streamer;
    }
    int getContentLen()
    {
        return contentLen;
    }
    bool initialize ()
    {
        // Code to update 'contentLen' by reading from source request object.
        // <code>
        if (streamer) streamer->initialize();
    }
    bool sendReq()
    {
        streamer->streamReq();
    }
    int getBytes (int nBytes)
    {
        // some code to read nBytes from the input source of this request object
    }
};

class RequestStreamer {
    Request* req;
    bool bEnabled;
    int chunkSize;

public:
    RequestStreamer(Request* aobj)
    {
        chunkSize = 1024*1024;
        req = aobj;
    }
    ~RequestStreamer()
    {
    }
    bool initialize()
    {
        if (req && req->getContentLen() > chunkSize)
            bEnabled = true;
    }
    bool streamReq()
    {
        if (!req) return false;

        // Assume that there exists socket object implementation already
        if (bEnabled)
        {
            while (req->getBytes(chunkSize) != -1)
                socket->send(req->getBytes(chunkSize));
        }
        else
        {
            socket->send(req->getBytes(req->getContentLen()));
        }
    }
};

最佳答案

根据您的代码:A还需要B的对象来初始化自身。 这意味着两个类之间存在关联 1 <-> 1。 这两个类都需要一个指向彼此的指针(这不是“B 帮助 A”,因为类之间有很强的相关性)。 但为了确保 RequestStreamer 只能由 Request 生成,请将其构造函数设为私有(private),并将 Request 设为友元类。

关于c++ - A 类的对象作为 B 类的成员。B 需要 A 的对象来初始化自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40706455/

相关文章:

design-patterns - 如果我有有限的时间学习一些设计模式,我应该学习哪些?

c# - 如何修改所有派生类中的方法返回值?

c++ - 转发声明/什么时候最好包含标题?

c++ - 为什么这行得通? C中的字符指针

java - C++代码覆盖工具

c++ - OpenCL clGetPlatformIDs 给出大约 230 个 valgrind memcheck 错误

c++ - 我可以使用 malloc 为类对象分配内存吗?

ruby-on-rails - Ruby on Rails 模式 - 装饰者与演示者

algorithm - 设计模式 : Generating daily and weekly tasks based on specifications

design-patterns - 存储库/模型中的业务逻辑好吗?