Click here to Skip to main content
15,896,154 members
Articles / Programming Languages / C++

Templates for Design Patterns

Rate me:
Please Sign up or sign in to vote.
2.47/5 (6 votes)
31 Jan 2006CPOL4 min read 54.4K   131   28  
A fly weight implementation of a C++ template library for applying Design Patterns easily in any application.
#ifndef TEMPLATE_PATTERNS_SINGLETON
#define TEMPLATE_PATTERNS_SINGLETON

/// Templated design pattern implementation for C++ version 0.2
/** (C) 2006 - Rasmus Christian Kaae, http://www.hestebasen.com/kaae/code.xml */
namespace template_patterns
{
  /// Singleton template class
  /** The singleton creates a singleton instance from a given class, T, and allows
  it to be reached globally and uniquely within the application. Say you have class C and want to turn it into a singleton,
  simply add the following code: <i>typedef singleton<C> c_singleton;</i>. Whenever you need to hook up with the singleton
  just write <i>c_singleton.instance().my_function(params);</i>.
  \param T class to allow singleton behaviour
  */
  template <class T> class singleton
  {
  public:
    /// Retrieve the instance
    /** \return the instance of type T
    */
    T & instance()
    {
      static T object;
      return object;
    }

    /// Retrieve the instance.
    /** \sa instance
        \return the instance of type T
    */
    T & operator* ()
    {
      return instance();
    }

    /// Retrieve the const instance.
    /** \sa instance
    \return the const instance of type T
    */
    const & operator* () const
    {
      return &instance();
    }
  };


};


#endif // TEMPLATE_PATTERNS_SINGLETON

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions