Crisp Reading Notes on Latest Technology Trends and Basics

Singletons

Introduction

Java uses the static methods and blocks as a primary primitive.
Singleton is built as a common design pattern on top of static methods.

Scala on the other hand builds the singleton as a standard pattern.
Static methods are implemented as methods within a singleton class

Objects versus Classes

Scala uses two keywords –  object and class to distinguish between singletons and non-singletons.

  • Defining an object defines a class and a singleton object with the same name
object Account {
  var count = 0

  def numAccounts(): Unit = {
    return count
  }
}
  • From the corresponding Account class, the count is added whenever an account is created
class Account(ssn:Int, balance:Float) {
  Account.count++;
  ...
}

Companion Classes

  • In the above example, the use of the same name for the object and the class is deliberate
  • These are called companion classes. They are present in the same file, and may access each others private methods

Singleton Objects in Other Domains

  • Singleton objects are used heavily used in CMIP, which is a OSI standard for sophisticated modeling
  • Singleton objects are also heavily used in Dependency-Injection Frameworks, such as Spring.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: