[GO] I wrote a design pattern in kotlin Singleton edition

To learn the concept of Interface and the reusability of objects, which are important in object orientation ["Introduction to design patterns learned in Java language"](https://www.amazon.co.jp/%E5%A2%97% E8% A3% 9C% E6% 94% B9% E8% A8% 82% E7% 89% 88Java% E8% A8% 80% E8% AA% 9E% E3% 81% A7% E5% AD% A6% E3% 81% B6% E3% 83% 87% E3% 82% B6% E3% 82% A4% E3% 83% B3% E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3% E5% 85% A5% E9% 96% 80-% E7% B5% 90% E5% 9F% 8E-% E6% B5% A9 / dp / 4797327030 / ref = sr_1_1? __mk_ja_JP =% E3% 82% AB % E3% 82% BF% E3% 82% AB% E3% 83% 8A & keywords = java% E8% A8% 80% E8% AA% 9E% E3% 81% A7% E5% AD% A6% E3% 81% B6 % E3% 83% 87% E3% 82% B6% E3% 82% A4% E3% 83% B3% E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3% E5 I learned about% 85% A5% E9% 96% 80 & qid = 1559563427 & s = gateway & sr = 8-1) and decided to write in Java and then in kotlin. This time I will summarize Singleton.

What is Singleton

A singleton is a term that refers to a set that has only one element, and is defined as a pattern that plays the following roles.

Singleton class

In this class, the singleton member defined as a static field is initialized with an instance of the Singleton class, but it is initialized only once when the class is loaded. In addition, it is guaranteed that only one instance will be created by preventing access from the outside with private.

For kotlin, there is no definition of static, instead define a companion object.

Reference: How to write static members in Kotlin?

Also, if you define companion object and decompile it, it will be accessed from getter / setter via Companion object, so const or @JvmField will be used. However, since const is only primitive type or String type, @JvmField is specified for non-primitive type, and if @JvmField is specified for primitive type, the initial value is assigned twice, so it is necessary to use it properly. However, @JvmField is used to give visibility to Field, so it could not be used in this private.

Reference: [Kotlin] [Java] Kotlin Java comparison memo Calling Kotlin from Java

__ Addendum: @sdkei Thank you for your review! __ After receiving a review, it is said that Kotlin can be implemented more easily by using object declaration even if it is not implemented as above. ⇒Singleton2.kt,SingletonSample2.kt

Reference: Design pattern with Kotlin Singleton Object Expressions and Declarations

Singleton.java


class Singleton {
	private static Singleton singleton = new Singleton();
	private Singleton() {
		System.out.println("You have created an instance.");
	}
	public static Singleton getInstance() {
		return singleton;
	}
}

Singleton.kt


class Singleton {
    init { println("You have created an instance.") }
    companion object {
       private val singleton = Singleton()
       fun getInstance() = this.singleton
    }
}

Singleton2.kt


object Singleton {
    init { println("You have created an instance.") }
}

Main class

SingletonSample.java


public class SingletonSample {
	public static void main(String[] args) {
		System.out.println("Start.");
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();
		if (s1 == s2) {
			System.out.println("s1 and s2 are the same instance.");
		} else {
			System.out.println("s1 and s2 are not the same instance.");
		}
		System.out.println("End.");
	}
}

SingletonSample.kt


fun main(args: Array<String>) {
    println("Start.")
    val s1 = Singleton.getInstance()
    val s2 = Singleton.getInstance()
    if (s1 == s2) println("s1 and s2 are the same instance.")
    else println("s1 and s2 are not the same instance.")
    println("End.")
}

SingletonSample2.kt


fun main(args: Array<String>) {
    println("Start.")
    val s1 = Singleton
    val s2 = Singleton
    if (s1 == s2) println("s1 and s2 are the same instance.")
    else println("s1 and s2 are not the same instance.")
    println("End.")
}

Execution result


Start.
You have created an instance.
s1 and s2 are the same instance.
End.

Class diagram

image.png

Impressions

  1. Define companion object {} instead of static
  2. In companion, specify const for primitive type and String type, and @JvmField for non-primitive type.
  3. If private, use as is
  4. The Singleton pattern can be easily used by object declaration.

reference

It was very easy to read and understand by referring to the following.

How should I write static members in Kotlin? [Kotlin] [Java] Kotlin Java comparison memo Calling Kotlin from Java Design pattern with Kotlin Singleton Object Expressions and Declarations

Recommended Posts

I wrote a design pattern in kotlin Singleton edition
I wrote a design pattern in kotlin Factory edition
I wrote a design pattern in kotlin Builder edition
I wrote a design pattern in kotlin Adapter edition
I wrote a design pattern in kotlin, Iterator edition
I wrote a design pattern in kotlin Template edition
I wrote a design pattern in kotlin Prototype
Design Pattern #Singleton
A memo that I wrote a quicksort in Python
I wrote a class in Python3 and Java
I wrote a Japanese parser in Japanese using pyparsing.
Singleton pattern in Python
I wrote python in Japanese
I wrote a script to get a popular site in Japan
I wrote a script that splits the image in two
I get a UnicodeDecodeError in mecab-python3
I get a KeyError in pyclustering.xmeans
Implement the Singleton pattern in Python
I wrote a function to load a Git extension script in Python
I wrote Fizz Buzz in Python
I wrote Gray Scale in Pytorch
I wrote a script to extract a web page link in Python
I wrote the queue in Python
I participated in AtCoder (ABC169 edition)
I wrote the stack in Python
I wrote a code to convert quaternions to z-y-x Euler angles in Python
[Python] I forcibly wrote a short Perlin noise generation function in Numpy.
I wrote FizzBuzz in python using a support vector machine (library LIVSVM).
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
[Gang of Four] Design pattern learning --Singleton
I want to print in a comprehension
Learn the design pattern "Flyweight" in Python
I made a payroll program in Python!
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Command" in Python
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
I wrote the selection sort in C
Learn the design pattern "Iterator" in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "Singleton" with Python
Learn the design pattern "State" in Python
I wrote Project Euler 1 in one liner.
Learn the design pattern "Adapter" in Python
I started Node.js in a virtual environment
I created a password tool in Python.
I wrote the sliding wing in creation.
[Fundamental Information Technology Engineer Examination] I wrote a linear search algorithm in Python.
I wrote a PyPI module that extends the parameter style in Python's sqlite3 module
When I get a chromedriver error in Selenium
Learn the design pattern "Abstract Factory" in Python
Delete data in a pattern with Redis Cluster
I want to create a window in Python
I tried playing a typing game in Python
Learn the design pattern "Factory Method" in Python