Home | History | Annotate | Download | only in base
      1 /*
      2  * libjingle
      3  * Copyright 2004--2010, Google Inc.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions are met:
      7  *
      8  *  1. Redistributions of source code must retain the above copyright notice,
      9  *     this list of conditions and the following disclaimer.
     10  *  2. Redistributions in binary form must reproduce the above copyright notice,
     11  *     this list of conditions and the following disclaimer in the documentation
     12  *     and/or other materials provided with the distribution.
     13  *  3. The name of the author may not be used to endorse or promote products
     14  *     derived from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #ifndef TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
     29 #define TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
     30 
     31 #include "talk/base/common.h"
     32 #include "talk/base/criticalsection.h"
     33 #include "talk/base/logging.h"
     34 #include "talk/base/scoped_ptr.h"
     35 
     36 namespace talk_base {
     37 
     38 template <typename Interface> class rcsf_ptr;
     39 
     40 // A ReferenceCountedSingletonFactory is an object which owns another object,
     41 // and doles out the owned object to consumers in a reference-counted manner.
     42 // Thus, the factory owns at most one object of the desired kind, and
     43 // hands consumers a special pointer to it, through which they can access it.
     44 // When the consumers delete the pointer, the reference count goes down,
     45 // and if the reference count hits zero, the factory can throw the object
     46 // away.  If a consumer requests the pointer and the factory has none,
     47 // it can create one on the fly and pass it back.
     48 template <typename Interface>
     49 class ReferenceCountedSingletonFactory {
     50   friend class rcsf_ptr<Interface>;
     51  public:
     52   ReferenceCountedSingletonFactory() : ref_count_(0) {}
     53 
     54   virtual ~ReferenceCountedSingletonFactory() {
     55     ASSERT(ref_count_ == 0);
     56   }
     57 
     58  protected:
     59   // Must be implemented in a sub-class. The sub-class may choose whether or not
     60   // to cache the instance across lifetimes by either reset()'ing or not
     61   // reset()'ing the scoped_ptr in CleanupInstance().
     62   virtual bool SetupInstance() = 0;
     63   virtual void CleanupInstance() = 0;
     64 
     65   scoped_ptr<Interface> instance_;
     66 
     67  private:
     68   Interface* GetInstance() {
     69     talk_base::CritScope cs(&crit_);
     70     if (ref_count_ == 0) {
     71       if (!SetupInstance()) {
     72         LOG(LS_VERBOSE) << "Failed to setup instance";
     73         return NULL;
     74       }
     75       ASSERT(instance_.get() != NULL);
     76     }
     77     ++ref_count_;
     78 
     79     LOG(LS_VERBOSE) << "Number of references: " << ref_count_;
     80     return instance_.get();
     81   }
     82 
     83   void ReleaseInstance() {
     84     talk_base::CritScope cs(&crit_);
     85     ASSERT(ref_count_ > 0);
     86     ASSERT(instance_.get() != NULL);
     87     --ref_count_;
     88     LOG(LS_VERBOSE) << "Number of references: " << ref_count_;
     89     if (ref_count_ == 0) {
     90       CleanupInstance();
     91     }
     92   }
     93 
     94   CriticalSection crit_;
     95   int ref_count_;
     96 
     97   DISALLOW_COPY_AND_ASSIGN(ReferenceCountedSingletonFactory);
     98 };
     99 
    100 template <typename Interface>
    101 class rcsf_ptr {
    102  public:
    103   // Create a pointer that uses the factory to get the instance.
    104   // This is lazy - it won't generate the instance until it is requested.
    105   explicit rcsf_ptr(ReferenceCountedSingletonFactory<Interface>* factory)
    106       : instance_(NULL),
    107         factory_(factory) {
    108   }
    109 
    110   ~rcsf_ptr() {
    111     release();
    112   }
    113 
    114   Interface& operator*() {
    115     EnsureAcquired();
    116     return *instance_;
    117   }
    118 
    119   Interface* operator->() {
    120     EnsureAcquired();
    121     return instance_;
    122   }
    123 
    124   // Gets the pointer, creating the singleton if necessary. May return NULL if
    125   // creation failed.
    126   Interface* get() {
    127     Acquire();
    128     return instance_;
    129   }
    130 
    131   // Set instance to NULL and tell the factory we aren't using the instance
    132   // anymore.
    133   void release() {
    134     if (instance_) {
    135       instance_ = NULL;
    136       factory_->ReleaseInstance();
    137     }
    138   }
    139 
    140   // Lets us know whether instance is valid or not right now.
    141   // Even though attempts to use the instance will automatically create it, it
    142   // is advisable to check this because creation can fail.
    143   bool valid() const {
    144     return instance_ != NULL;
    145   }
    146 
    147   // Returns the factory that this pointer is using.
    148   ReferenceCountedSingletonFactory<Interface>* factory() const {
    149     return factory_;
    150   }
    151 
    152  private:
    153   void EnsureAcquired() {
    154     Acquire();
    155     ASSERT(instance_ != NULL);
    156   }
    157 
    158   void Acquire() {
    159     // Since we're getting a singleton back, acquire is a noop if instance is
    160     // already populated.
    161     if (!instance_) {
    162       instance_ = factory_->GetInstance();
    163     }
    164   }
    165 
    166   Interface* instance_;
    167   ReferenceCountedSingletonFactory<Interface>* factory_;
    168 
    169   DISALLOW_IMPLICIT_CONSTRUCTORS(rcsf_ptr);
    170 };
    171 
    172 };  // namespace talk_base
    173 
    174 #endif  // TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
    175