第五章,技术
26-限制某个class所能产生的对象数量
实现0个对象限制
class Printer { public: ... private: Printer() {} };
|
实现单一对象限制
实现单一对象限制的最有效方法就是将constructor变成private,并提供获取单一对象的接口
class Printer { public: static Printer& getInstance() { static Printer instance; return instance; } ... private: Printer() {} };
|
实现对象数量(n>1)限制
可复用的计数器基类模板设计
template <class BeingCounted> class Counted { public: class TooManyObjects {}; static int objectCount() { return numObjects; } protected: Counted() { init(); } Counted(const Counted& rhs) { init(); } ~Counted() { --numObjects; }
private: static int numObjects; static const int maxObjects; void init() { if (numObjects >= maxObjects) throw TooManyObjects(); ++numObjects; } };
|
限制10个Printer对象
class Printer : private Counted<Printer> { public: static Printer* makePrinter() { return new Printer(); } using Counted<Printer>::objectCount; using Counted<Printer>::TooManyObjects; private: Printer() {} };
template<> const int Counted<Printer>::maxObjects = 10; template<> int Counted<Printer>::numObjects = 0;
|