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/