1 Context Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
2 Problem description In this study, you need to develop a program that will calculate coins using the ’Singleton Pattern’. Adding coins will be increased by 10 points, but decreasing by one point will be reduced. You should try 3 approaches of Singleton while developing this program. ∗ Eager initialization ∗ Lazy Initialization ∗ Thread Safe Singleton
Eager initialization
public class Main
{
public static void main(String[] args) {
SingleObject object = SingleObject.getInstance();
object.addCoins(3);
object.decrease(2);
}
}
class SingleObject {
private int coins;
private static SingleObject instance = new SingleObject(3);
private SingleObject(int c){
coins=c;
}
public static SingleObject getInstance(){
return instance;
}
public void addCoins(int c){
coins=coins+c;
System.out.println("The number of coins is "+coins);
}
public void decrease(int c){
coins=coins-c;
System.out.println("The number of coins is "+coins);
}
}
Lazy Initialization
public class Main
{
public static void main(String[] args) {
SingleObject object = SingleObject.getInstance();
object.addCoins(3);
object.decrease(2);
}
}
class SingleObject {
private int coins;
private static SingleObject instance;
private SingleObject(int c){
coins=c;
}
public static SingleObject getInstance(){
if(instance == null){
instance = new SingleObject(3);
}
return instance;
}
public void addCoins(int c){
coins=coins+c;
System.out.println("The number of coins is "+coins);
}
public void decrease(int c){
coins=coins-c;
System.out.println("The number of coins is "+coins);
}
}
Thread Safe Singleton
public class Main
{
public static void main(String[] args) {
SingleObject object = SingleObject.getInstance();
object.addCoins(3);
object.decrease(2);
}
}
class SingleObject {
private int coins;
private static SingleObject instance;
private SingleObject(int c){
coins=c;
}
public static synchronized SingleObject getInstance(){
if(instance == null){
instance = new SingleObject(3);
}
return instance;
}
public void addCoins(int c){
coins=coins+c;
System.out.println("The number of coins is "+coins);
}
public void decrease(int c){
coins=coins-c;
System.out.println("The number of coins is "+coins);
}
}
Comments
Leave a comment