Singleton

A singleton class is one which can be instantiated only once. This is useful when exactly one object is needed to coordinate actions across the system.

Steps to acheive singleton class

1. Make constructor private.

2. Add a synchronized method to provide instance.

3. Disable cloning of current class object.

Java code for singleton class

package test;
class Fruit
{
    private String name;
    private static Fruit instance = null;

    private Fruit() {
        name = null;
    }

    public static synchronized Fruit getInstance() {
        if(instance == null)
            instance = new Fruit();
        return instance;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // If super class is Cloneable then stop the cloning
    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    @Override
    public String toString() {
        return name;
    }
}
public class SingletonExample
{
    public static void main(String[] args)
    {
        Fruit fruit = Fruit.getInstance();
        fruit.setName("Mango");
        System.out.println(fruit);
    }
}

Comments

  1. check other implementations of singleton too.
    the one uve mentioned is a trivial one and has been improved upon.

    ReplyDelete

Post a Comment

Popular posts from this blog

Index MySQL datadase table in Solr

Hibernate Sharding Example

Shallow Copy