Advertisement
homer512

private ctor factory

Jul 4th, 2014
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. namespace {
  2.  
  3.   class Factory;
  4.  
  5.   class FactoryKey
  6.   {
  7.     friend class Factory;
  8.   private:
  9.     /* Only Factory can build one */
  10.     FactoryKey() {}
  11.     /* Prevent "stealing" a key by copying it */
  12.     FactoryKey(const FactoryKey&);
  13.   };
  14.  
  15.   class Base
  16.   {
  17.   protected:
  18.     /* Prevent construction by anyone who cannot provide a FactoryKey */
  19.     Base(const FactoryKey&) {}
  20.   public:
  21.     virtual ~Base() {}
  22.   };
  23.  
  24.   class Derived: public Base
  25.   {
  26.   public:
  27.     Derived(const FactoryKey& key)
  28.       : Base(key)
  29.     {}
  30.     virtual ~Derived() {}
  31.   };
  32.  
  33.   class Factory
  34.   {
  35.   public:
  36.     template<class T>
  37.     T* build()
  38.     {
  39.       return new T(FactoryKey());
  40.     }
  41.   };
  42.  
  43. }
  44.  
  45. int main()
  46. {
  47.   Factory fact;
  48.   fact.build<Derived>();
  49.   new Derived(FactoryKey()); /* <--- error: FactoryKey() is private here */
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement