To avoid eagerly creating of singleton object, The object creation needs to be on-demand. in the below code, the object creation will only happen when the getAppleInstance
method will be called, but the getAppleInstance
method can be called multiple times and it can be used to create multiple Singleton
objects as shown below.
package org.wesome.dsalgo.design.pattern.singleton;
public class Apple {
static Apple appleInstance;
public Apple() {
System.out.println("Apple default constructor");
}
public static Apple getAppleInstance() {
System.out.println("Apple getAppleInstance");
appleInstance = new Apple();
return appleInstance;
}
}
package org.wesome.dsalgo.design.pattern.singleton;
public class SingletonClass {
public static void main(String[] args) {
System.out.println(Apple.getAppleInstance());
System.out.println(Apple.getAppleInstance());
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.4.1"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}
To avoid multiple calls to the getAppleInstance
method, an object nullability can be checked, it will prohibit the repeated instance creation.
package org.wesome.dsalgo.design.pattern.singleton;
import java.util.Objects;
public class Apple {
static Apple appleInstance;
public Apple() {
System.out.println("Apple default constructor");
}
public static Apple getAppleInstance() {
System.out.println("Apple getAppleInstance");
if (Objects.isNull(appleInstance)) {
appleInstance = new Apple();
}
return appleInstance;
}
}
package org.wesome.dsalgo.design.pattern.singleton;
public class SingletonClass {
public static void main(String[] args) {
System.out.println(Apple.getAppleInstance());
System.out.println(Apple.getAppleInstance());
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.4.1"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}