All stories
Java

Singleton

H
hemant-kumar

September 6, 2012

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

0

If you found this helpful, give it some claps!

SHARE THIS ARTICLE

Share on X
LinkedIn

Responses0

Sign in to join the conversation

Sign in