Singleton class in many programming languages

A singleton object can exist exactly once during a programs execution. A singleton

  1. Needs to be only initialized once – Only one object is ever created
  2. Needs to be accessed (with the same data) by several different functions and objects

Below is the code to create a singleton class.

Java Singleton Class

public final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");

    public static Foo getInstance() {
        return INSTANCE;

PHP singleton class

class User
    // Hold an instance of the class
    private static $instance;
    // The singleton method
    public static function singleton()
        if (!isset(self::$instance)) {
            self::$instance = new __CLASS__;
        return self::$instance;

C++ singleton class

class Singleton

   static Singleton& instance()
      static Singleton INSTANCE;
      return INSTANCE;

Python singleton class

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance

if __name__ == '__main__':
        print "Same"
        print "Different"


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>