public final class MyClassSingleton {
private static MyClassSingleton INSTANCE;
private String msg = "Info class";
private MyClassSingleton() {
}
public static MyClassSingleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new ClassSingleton();
}
return INSTANCE;
}
}
public enum EnumSingleton {
INSTANCE("Сlass enum info");
private String msg;
private EnumSingleton(String msg) {
this.msg = msg;
}
public EnumSingleton getInstance() {
return INSTANCE;
}
}
MyClassSingleton classSingleton1 = MyClassSingleton.getInstance();
System.out.println(classSingleton1.getMsg()); // "Info class";
MyClassSingleton classSingleton2 = MyClassSingleton.getInstance();
classSingleton2.setInfo("New class message");
System.out.println(classSingleton1.getMsg()); //New class message
System.out.println(classSingleton2.getMsg()); //New class message
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance();
System.out.println(enumSingleton1.getInfo()); //Сlass enum info
EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance();
enumSingleton2.setInfo("New info");
System.out.println(enumSingleton1.getInfo()); // New info
System.out.println(enumSingleton2.getInfo()); // New info
public synchronized static MyClassSingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new MyClassSingleton();
}
return INSTANCE;
}