** Table of Contents ** The last of the creational patterns is a singleton. I think this is a pattern that everyone is familiar with. I feel that the first design pattern I learned was a singleton.
Classes that provide DB connections and classes that get assets are generally implemented in this pattern. Guarantees the uniqueness of an instance of that class in your program.
It guarantees that there is only one instance for a class and provides a global way to access it.
ยท A class that creates only one Singleton instance
If you code this pattern in kotlin, it will be in a simple form as shown below, so I'm not sure, so I will code it in java.
SingletonObject.kt
package singleton
object SingletonObject {
var str = ""
fun print() {
println("Output result:$str")
}
}
Create images and music files from multiple screens via singleton objects.
Singleton object
JavaSingletonObject.java
package singleton;
public class JavaSingletonObject {
/**
*Defined as static and make the instance of own class unique
*/
public static JavaSingletonObject instance = new JavaSingletonObject();
private String address = "/assets/temp";
enum Assets {
IMAGE1("image_1"),
IMAGE2("image_2"),
AUDIO1("audio_1"),
AUDIO2("audio_2");
private final String value;
Assets(final String value) {
this.value = value;
}
}
/**
*Define the constructor privately so that no new instance can be created.
*/
private JavaSingletonObject(){
System.out.println("Connection:" + address);
}
public String getAssets(Assets target) {
System.out.println("Material acquisition with singleton object:" + target.value);
return target.value;
}
}
Screen 1 class
DisplayOne.kt
package singleton
class DisplayOne {
fun draw() {
println("In User1${JavaSingletonObject.instance.getAssets(JavaSingletonObject.Assets.IMAGE1)}Draw!!")
}
}
Screen 2 class
DisplayTwo.kt
package singleton
class DisplayTwo {
fun start() {
println("In User2${JavaSingletonObject.instance.getAssets(JavaSingletonObject.Assets.AUDIO1)}Play!!")
}
}
Screen management class
Manager.kt
package singleton
class Manager {
init {
DisplayOne().draw()
DisplayTwo().start()
}
}
This completes the implementation of the singleton pattern. This process is supposed to be executed only once because the connection to assets is established in the constructor of the `` `JavaSingletonObject``` class.
Also, since the constructor is defined as private, it is not possible to create a new instance of the class, and uniqueness is guaranteed.
[output]
Connection:/assets/temp
Material acquisition with singleton object: image_1
Image in User1_Draw 1!!
Material acquisition with singleton object: audio_1
Audio with User2_Play 1!!
Recommended Posts