(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Singleton

Description: The classic singleton design pattern.

Keywords: ecl singleton

Tutorial Level: INTERMEDIATE

Overview

Singletons are a means of ensuring a single, unique copy of an object can ever exist. There are various ways of implementing singletons, the wikipedia has a surprisingly good article on singletons and provides a snippet that utilises the curiously recurring template pattern which is used as the derivation for this form of the singleton.

Compiling & Linking

Include the following at the top of any translation unit that:

   1 #include <ecl/utilities.hpp>
   2 
   3 using ecl::Singleton;

Usage

Inheriting

This singleton is intended to be inherited by a deriving class - this saves the work of actually reinventing the singleton mechanisms whenever you wish to use a singleton.

   1 class TestObject : public ecl::Singleton<TestObject>
   2 {
   3 friend class ecl::Singleton<TestObject>;
   4 
   5 public:
   6     int value() { return data; }
   7 
   8 protected:
   9     TestObject() : data(32) {}
  10 
  11 private:
  12     int data;
  13 };

Calling

If you use a macro as shown below, the instance can be conveniently and readably accessed,

   1 #define Test TestObject::instance()
   2 
   3 ...
   4 
   5 cout << Test.value() << endl;

Wiki: ecl_utilities/Tutorials/Singleton (last edited 2012-02-01 13:54:33 by DanielStonier)