2

I am implementing a library following a template method design pattern. It involves creating costly IO connection. To avoid any resource leaks, i want to enforce singleton instance on abstract class level. client just need to override the method which involves logic.

how can i do with kotlin?

abstract class SingletonConnection{
     fun start(){ /* code */ }
     fun connect(){ /* code */ }
     abstract fun clientLogic()   
}

If class A extends this, it should be singleton class. not allowed to initialise multiple times. how to do in kotlin?

Rajeev
  • 4,762
  • 8
  • 41
  • 63

3 Answers3

1

Unfortunately, there is no way to enforce that only objects (singletons in Kotlin) can inherit from a certain abstract/open class or interface in Kotlin. object declaration is just syntactic sugar for a regular class with a Singleton pattern.

I know it's not much, but I guess you can achieve this to a certain degree by adding documentation, asking users to implement this class by Singletons alone.

By the way, I would use an interface instead of an abstract class for this purpose.

Gil Becker
  • 283
  • 1
  • 9
  • how interface will improve the design? – Rajeev Sep 07 '20 at 14:58
  • 1
    I believe you should always use interfaces over abstract classes when possible (see Effective Java Item #20). The main point is that an interface allows multiple inheritance (in contrast to classes), and in Kotlin you can write default implementations to functions in interfaces. – Gil Becker Sep 08 '20 at 09:13
0

Instead of creating abstract class just change the code like this:-

object SingletonConnection{
     fun start(){ /* code */ }
     fun connect(){ /* code */ }
     fun clientLogic()   
}

It will provide the same implementation which you want to achieve using abstract class.

Also get the method using this code:-

SingletonConnection.start()
Pawan Soni
  • 860
  • 8
  • 19
  • 1
    He wants to allow clients to inherit from SingletonConnection, but you cannot implement objects. Also, you cannot have a function with no implementation. – Gil Becker Sep 07 '20 at 14:57
0

You can use an object that extends from your abstract class. Your abstract class:

abstract class SingletonConnection {
    fun start(){ /* code */ }
    fun connect(){ /* code */ }
    abstract fun clientLogic()
}

Kotlin object (this object will be the singleton):

object Connection: SingletonConnection() {
    override fun clientLogic() {
        // TODO
    }
}

Usage (creation of the object occurs at the first call):

override fun onCreate() {
    ...

    // here object creation
    Connection.start()

    ...setOnClickListener {
        Connection.clientLogic()
    }
}
Andy Pro
  • 55
  • 7