下面是根据您在其中一条评论中提到的工厂构思提出的另一个答案。它采用Facade模式集中在绑定到一个Session
一个System
类的系统设备创建:
#include <boost/shared_ptr.hpp>
class System
{
public:
typedef boost::shared_ptr<pf_ostream> pf_ostream_ptr;
typedef boost::shared_ptr<pf_istream> pf_istream_ptr;
// Other system facilities...
System(Session* session) : session_(session) {}
pf_ostream_ptr makeOstream()
{return pf_ostream_ptr(new pf_ostream(session_));}
pf_istream_ptr makeIstream()
{return pf_istream_ptr(new pf_istream(session_));}
private:
Session* session_;
};
class Plugin
{
public:
Plugin(System* system) : system_(system) {}
System& system() {return *system_;}
private:
System* system_;
};
class MyPlugin : public Plugin
{
public:
MyPlugin(System* system) : Plugin(system) {}
void print()
{
pf_ostream_ptr pfos(system().makeOstream());
*pfos << "Hello World!\n";
// pfos will be deleted automatically at the end of this scope
}
};
如果你有很多的系统设施,你应该明智地使用着的声明,以避免长时间的编译时间。此解决方案的缺点是将您的系统设施集中在一个依赖关系“焦点”(System
类)中。如果System
类在使用更多或更少系统设施的其他应用程序中重新使用,则可能需要更改该类。
编辑:
这里是你如何运用代理模式(以及PIMPL方法)来获取值语义的引用计数的流类:
#include <boost/shared_ptr.hpp>
class pf_ostream
{
public:
pf_ostream(Session* session);
pf_ostream& operator<<(int rhs);
// Use of default copy-constuctor and assignment operator
// will work fine because of shared_ptr.
private:
struct Impl;
boost::shared_ptr<Impl> pimpl_;
};
// In cpp file
struct pf_ostream::Impl
{
Impl(Session* session) : session(session) {}
void insert(int rhs) {/*...*/}
Session* session;
};
pf_ostream::pf_ostream(Session* session) : pimpl_(new Impl(session)) {}
pf_ostream& pf_ostream::operator<<(int rhs) {pimpl_.insert(rhs); return *this;}
用户将必须意识到代理对象的副本将引用相同的实际流。希望这可以帮助。
你能举一个例子来说明这是怎么完成的吗? – 2010-04-20 16:05:46
嗯,看着它,它看起来像你仍然需要显式传递一个指向封闭类的指针。我正在寻找通过内部类构造函数不可见的内容。 – 2010-04-20 16:13:39
在我的系统中,外部类是实例化为插件的实际类的父类,因此用户必须明确地传递插件引用。 – 2010-04-20 16:20:19