Created
March 17, 2015 03:22
-
-
Save granthenke/a26d36654a2671894e64 to your computer and use it in GitHub Desktop.
Client Reuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Client(connection: String) { | |
println("New Client: " + connection) | |
} | |
object Client { | |
private val clients = new mutable.HashMap[String, Client]() | |
def apply(connection: String): Client = { | |
clients.getOrElse(connection, createClient(connection)) | |
} | |
private def createClient(connection: String): Client = { | |
val client = new Client(connection) | |
clients.put(connection, client) | |
client | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok so lazy val cant take param so your approach is fine. Another approach would be as follow. The only advantage of this approach is that Scala is taking care of synchronization. Your approach has a small threading issue and apply should really be synchronized