Design Pattern with Kotlin

Design Pattern With Kotlin

ahmed shaaban
The Startup

--

1- singleton design pattern and its rule.
2- way to make singleton thread-safe
3- implementation in Kotlin without object keyword and the magic of object
3- how to Call Kotlin object Singleton in java class
4- Kotlin object property.
5- tricky ways to handle singleton when need to pass args to param
6- when it is not recommended to use object ?
7- android real example you do in your app (retrofit and sharedPref)

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

use this Design pattern when application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.

Rule of Singleton class

  1. A private constructor
  2. A static reference of its class
  3. One static method
  4. Globally accessible object reference
  5. Consistency across multiple threads

Deal with multiple threads(singleton thread safe)

The Singleton is probably the easiest pattern to initially understand, but can be dangerously easy to overuse — and abuse. Since it’s accessible from multiple objects, the singleton can undergo unexpected side effects that are difficult to track down — exactly what Future You doesn’t want to deal with.

1- use synchronized block synchronized(this){} called ”Double-Checked Locking”
2- use annotation
@Synchronized also called “Double-Checked Locking”
3-
Eagerly Create an Instance so make instance_variable = SingletonClass()
4- use @Singleton annotation in Dagger2
5- use object in class make class singleton and thread safe
6- use static initialization block in java not in kotlin

a Kotlin object actually relies on a Java static initialization block.t enables thread-safe lazy initialization without having to rely on a locking algorithm like the complex double-checked locking.

using object instead of all this The Kotlin object keyword is used to declare a singleton, without the need to specify a static instance

how to Call kotlin object Singleton in java class ??

Singleton.doSomeThin()

Behind the scenes, the Kotlin object is backed by an INSTANCE static field, so if you need to use a Kotlin object from Java code, you modify the call as follows:

Singleton.INSTANCE.doSomeThin() 

we can create a singleton class based on initialization-on-demand holder pattern. but using object instead as object gets instantiated when it is used for the first time. but i do it to play with Kotlin 😇😇

Kotlin object property

  • Kotlin’s representation of a Singleton class requires the object keyword only.
  • The object will be instantiated and its init blocks will be executed lazily upon first access
  • An object class can contain properties, functions and the init method.
  • The constructor method is NOT allowed.
  • A singleton object can be defined inside a class. It cannot be defined inside an inner class.
  • An object cannot be instantiated in the way a class is instantiated.
  • An object gets instantiated when it is used for the first time.

tricky ways to handle singleton when need to pass args to param

  • use first way i use without using object keyword and pass args to function that check if there is instance of object or not
    getInstance(args)
  • use normal way by using object class but make function that will be used one time like in shared pref make init(val context:Context) and call it in application class
  • use initialization-on-demand holder and when i search on internet i found code that implemented like the implementation of lazy in Kotlin

this is not my code i found it in internet but i will use it in shared Pref example at the end but it is awesome idea ❤️

see the implementation for lazy here

when it is not recommended to use object

  • the concrete implementation of the singleton is generated by an external tool or library like Retrofit and Room and its instance is retrieved using a custom builder or factory method. In that case, you usually declare the singleton as an interface or abstract class and it can’t be an object.
  • singleton instance directly goes against the principle of dependency injection, therefore it’s likely to become a problem. But an object presents an even bigger constraint, because it must be accessed as a singleton.
  • an object is necessarily final. This means that it’s impossible to extend from it.

android real example you do in your app.

1- retrofit i know i said not use retrofit with object but i will make article for using interface to make Singleton next time

2- shared pref (use Singleton Holder)
One powerful feature that Kotlin companion objects offer is their ability to inherit from a base class

companion object : SingletonHolder<PrefsHelper, Context>(::PrefsHelper)

3- Dagger2 use @Singleton and if you appComponent make it object

@Provides
@Singleton
public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson) {
return new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.baseUrl("you/base/url")
.build();
}

Awesome code for SingletonHolder found it in
https://blog.mindorks.com/how-to-create-a-singleton-class-in-kotlin

--

--