Java Singleton Template for Eclipse
private static ${enclosing_type} instance; private ${enclosing_type}(){} public static ${enclosing_type} getInstance(){ if(null == instance){ instance = new ${enclosing_type}(); } return instance; }
11453 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
private static ${enclosing_type} instance; private ${enclosing_type}(){} public static ${enclosing_type} getInstance(){ if(null == instance){ instance = new ${enclosing_type}(); } return instance; }
public class MySingleton { private static final MySingleton INSTANCE = new MySingleton(); private MySingleton() {} public static final MySingleton getInstance() { return INSTANCE; } /** * Normal deserialization returns a new instance of an object. This ensures that only one instance is in existence. * Deserialization can either create a new instance and leave the deserialized object to be garbage collected or * reuse the deserialized instance. */ private Object readResolve() throws ObjectStreamException { return INSTANCE; } }
class Singleton private_class_method :new @@singleton = nil def Singleton.create @@singleton = new unless @@singleton @@singleton end end
class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state
>>> b = Borg() >>> b.x = 1 >>> c = Borg() >>> c.x 1
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state a=Borg() a.toto = 12 b=Borg() print b.toto print id(a),id(b) # different ! but states are sames
class Singleton(object): def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance a=Singleton() a.toto = 12 b=Singleton() print b.toto print id(a),id(b) # the same !!
/** * Singleton Repository * @param string $class PHP Class Name * @param string $id Optional Object ID * @return reference Reference to existing Object */ function &Singleton($class, $id='') { static $singleton = array(); if (!array_key_exists($class.$id, $singleton)) $singleton[$class.$id] = &new $class(); $reference = &$singleton[$class.$id]; return $reference; }
# first call: create object $site_user=&Singleton('Student'); $site_user->Drink_Beer(5); # second call: get a reference $current_user=&Singleton('Student'); echo $current_user->Show_Beers_Counter(); #will be 5 #Two different objects $one=&Singleton('Some_Class','one'); $two=&Singleton('Some_Class','two');