[BAEL-1066] Implementing Singleton pattern in Java (#2361)

* Different Types of Bean Injection in Spring code

* Dataclasses in Kotlin

* Revert "Different Types of Bean Injection in Spring code"

This reverts commit 4b747726b93a9f6bf76d6518792fc77e0d5c2fc9.

* Destructuring Declarations in Kotlin

* Corrections on Destructuring Declarations in Kotlin

* Implementing Singleton pattern in Java

* [BAEL-1066] Implementing Singleton pattern in Java

* Singleton Implementation changes.
This commit is contained in:
cleversonzanon 2017-08-07 18:14:57 -03:00 committed by Grzegorz Piwowarek
parent 2263b24c9f
commit 1824320f95
3 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package com.baeldung.designpatterns.singleton;
public class ClassSingleton {
private static ClassSingleton INSTANCE;
private String info = "Initial class info";
private ClassSingleton(){
}
public static ClassSingleton getInstance(){
if(INSTANCE == null){
INSTANCE = new ClassSingleton();
}
return INSTANCE;
}
// getters and setters
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.designpatterns.singleton;
public enum EnumSingleton {
INSTANCE("Initial enum info"); //Name of the single instance
private String info;
private EnumSingleton(String info) {
this.info = info;
}
public EnumSingleton getInstance(){
return INSTANCE;
}
//getters and setters
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.designpatterns.singleton;
public class Sandbox {
public static void main(String[] args) {
//Class singleton
ClassSingleton classSingleton1 = ClassSingleton.getInstance();
//OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible
System.out.println(classSingleton1.getInfo()); //Initial class info
ClassSingleton classSingleton2 = ClassSingleton.getInstance();
classSingleton2.setInfo("New class info");
System.out.println(classSingleton1.getInfo()); //New class info
System.out.println(classSingleton2.getInfo()); //New class info
//Enum singleton
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance();
System.out.println(enumSingleton1.getInfo()); //Initial enum info
EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance();
enumSingleton2.setInfo("New enum info");
System.out.println(enumSingleton1.getInfo()); //New enum info
System.out.println(enumSingleton2.getInfo()); //New enum info
}
}