Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Java Singleton Template for Eclipse

This is a template for easily creating an implementation of the Singleton Pattern on Eclipse. Open Window->Preferences->Java->Editor->Templates click on New and insert the code below on the pattern text area; add a name (I suggest "singleton") - whenever you type this name and press Ctrl+Space the code will be inserted in your class - and you're good to go.

private static ${enclosing_type} instance;

private ${enclosing_type}(){}

public static ${enclosing_type} getInstance(){
	if(null == instance){
		instance = new ${enclosing_type}();
	}
	return instance;
}

Singleton

The proper way of implementing a Singleton.

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;
	}
}

singleton in ruby

// simple singleton

class Singleton 
  private_class_method :new
  @@singleton = nil
  
  def Singleton.create
    @@singleton = new unless @@singleton
    @@singleton
  end
end

Singleton pattern in python

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

What a pythonic way to use Singleton. It uses shared-state
approach where you can actually have many instances as you want
but they all share the same state. See Alex's recipe.
>>> b = Borg()
>>> b.x = 1
>>> c = Borg()
>>> c.x
1

python singleton and singleton borg

Singleton with same states
# 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



real Singleton instance
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 !!




Flexible Singleton

PHP function Singleton allows you holding exactly one object of a class in memory. If an object of a given class doesn't exist, Singleton will create and store a new one in static array singleton. It then (and otherwise) will return a reference to it.

Adding an optional ID allows holding more than one object a class. Assigned ID will distinguish array keys.

/**
 * 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;
}


Use like this:
[edit] I'm sorry there was a mistake in the first exmaple for three days or so. Fixed.
# 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');


Works fine with PHP4, not tested on PHP5
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS