The getAppleInstance
method will make sure the instance should be unique. but the Apple class still have public default constructor, which can be called to create a new object of Singleton
class as 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");
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());
Apple apple = new Apple();
System.out.println("apple = " + apple);
}
}
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 stop multiple creations of Singleton
objects using a public constructor
, The constructor
will be private
, so that it cannot be called outside of the class. In the below code, the object creation will only happen when the getAppleInstance
method will be called.
package org.wesome.dsalgo.design.pattern.singleton;
public class Apple {
static Apple appleInstance;
private Apple() {
System.out.println("Apple private 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());
/* private constructor is not accessible outside the Apple class, hence below line will throw compile time exception */
Apple apple = new Apple();
System.out.println("apple = " + apple);
}
}
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()
}