Object creational design patterns

Object creation patterns deal with the creation of objects. Through these patterns you get finer control on how objects are being created and made available. These patterns essentially give you controls such as limiting the number of instances of the class, time of instance creation – on demand vs lazy, initialization on object creation, selection of concrete implementation to be instantiated at run time and so on.

Singleton (Limiting number of instance)
  • When to use
    • Only one object of the class is required per application.
    • Provide global point of access for classes representing internal resource such as logger or external resources such as network connections.
  • Special scenarios
      • Multiple threading environment – double locking mechanism commonly used.
      • Multiple class loader scenario – Have a common parent classloader loading the singleton.
      • Serialization – Override Serializable#readResolve method to provide the same instance on de-serialization
      • Clustered environments – Most of the app servers provide mechanisms to achieve Singleton across clustered JVMs. One such mechanism provided by jboss is HASingleton service. More details.
  • References
Multiton (Limiting number of instance)
  • This is variant of Singleton pattern.
  • Allows creation of number of named instances of single class which are managed in a map as key-value pair.
  • This is useful esp in scenario where the behavior or state of the object changes with one or two criticial inputs which are essentially keys.
  • Reference
Singleton Registry (Limiting number of instance)
  • This is variant of Multiton pattern but manages instance (one) of classes.
  • Allows creation of number of singleton instances from different classes and managed in a map as key-value pair. This map serves as a registry.
  • This is useful when you want to have a singleton registry system-wide.
  • A good example of this implementation is OSGi service registry.
Object Pool (Limiting number of instance)
  • Object pool limits the maximum number of instances of a class to the set N number. Most of the times N is configurable.
  • Usually, this is applied to classes which represent expensive system resources such as handle, thread or connection.
  • Behavior – When an instance of the class is asked by the consuming class, Object pool checks if the pool is full, if not it creates an instance return it. If the pool is full, the consuming class has to wait till an object in the pool becomes available. Once an instance is shared with the consuming class, consuming classes uses it and frees it once it’s job is done. Once freed, the instance becomes available to the pool ensuring re-use.
  • JDK examples
    • Thread pool. Link.
    • Database connection pool.
  • Reference
Lazy Initialization (Initialization)
  • Also called as on-demand initialization.
  • Creating objects only when it’s accessed for the first time (vs eager initialization).
  • Lazy initialization is preferred as it provides significant performance gain.
  • Lazy loaded singleton is a good example of this.
  • Reference
    • Eager vs Lazy initailization – Java world. Link.
Prototype (Initialization)
  • Prototype pattern is about creating clone of an existing object instead of creating a new one.
  • It’s applied when creating a new object is expensive than creating a clone.
  • In java, this pattern is implemented via Cloneable interface. Remember the implementation provided by java Object superclass (java.lang.Object#clone) is shallow copy. Deep copy needs custom implementation of Cloneable interface for your objects.
  • Reference
Dependency Injection (Initialization)
  • Dependency injection involves resolving dependencies of a class through container created  objects. An object would depend on number of other objects. When the object gets initialized, the dependency objects are created by the container and injected into the object. It follows inversion of control design principle.
  • Dependency Injection allows easy testing of classes.
  • Typical examples
    • OSGi – Services are usually singleton maintained in a registry (Service registry). For an OSGi component, the run time (container), injects the dependencies (objects) in to the object being created. OSGi run time reuses objects as they are singletons.
    • Spring dependency injection – Sprint IoC container creates objects and wire them to the object being created.
Factory (Selection of concrete implementation)
  • It’s one of the most used patterns.
  • When to use
    • Hide the instantiation logic from consuming classes.
    • Program to abstraction and allow selection of concrete class independent of the consuming classes.
  • Factory implementations are mostly singletons.
  • Implementation hints
    • A simple switch case. This would need changes whenever new product (object to be created) are added.
    • Reflection based where no change in factory required for the addition of new product object to be created)
  • JDK examples
    • java.util.Calendar#getInstance
    • java.net.URLStreamHandlerFactory
  • References
Factory Method (Selection of concrete implementation)
Abstract Factory (Selection of concrete implementation)
Factory Vs Factory method Vs Abstract Factory
  • All of them deal with the creation of objects and hides the logic of selecting the suitable concrete implementation from the client.
  • Factory
    • Mostly implemented as singleton and becomes single point of reference for creating objects.
    • Factory creates object of concrete classes and returns them as abstracted type.
  • Factory method
    • Factory allows sub-classing and forces the concrete factory to create objects of concrete classes.
    • Most of the times, concrete factory involves bit of processing based on the method argument to choose the right concrete class for instantiation.
  • Abstract factory
    • It’s called factory of factories.
    • Groups factories and its related concrete classes together providing abstraction at the top.
  • Reference
Lazy Factory (Selection of concrete implementation)
  • It’s a combination of 3 patterns – Factory method, multiton and lazy initialization.
  • Instances are created applying the factory method. Objects are created only on demand following lazy initialization. Created objects are stored in a map following multiton pattern.
Builder (Object construction)
  • Object construction essentially requires series of method invocation in the object so that object is in a state which is usable,
  • Purpose of builder pattern is to allow creation of multiple representation of an object through a single construction process.
  • Actors
    • Director – Single. Takes care of construction process.
    • Builder – Multiple concrete implementations. Each builder builds different representation of the product.
    • Product – Object to be built. Multiple object belong the single class considered.
  • Examples
    • Vehicle manufacturing assembly lane. Assembly lane (Director) creates multiple representation of the product (Vehicle) based on the builder chosen.
    • Building JSON (Director) representing financial data needed to present web page for reporting different instruments (Building) such as Mutual Funds, Money Market Funds, Closed End Funds, etc. (Products).
      • Product – Funds. Example – Mutual Funds, Money Market Funds, Closed End Funds, etc.
      • Director – JsonDataConstrctor. Responsible for composing entire JSON response for the AJAX request from the web page for different web pages.
      • Builder – MutualFundJsonBuilder, MoneyMarketJsonBuilder, etc.
    • Reference
Self Builder (Object construction)
  • A variant of the above builder pattern is proposed in highly regarded “Effective Java” book by Joshua Bloch.
  • Per the pattern, the class to be instantiated has a static inner class to deal with the object construction.
  • Where to use
    • The class has number of mandatory arguments which lead to telescoping constructor (anti-pattern). Telescoping constructor is an anti-pattern where there are overloaded constructor with varying number of arguments.
  • Reference
    • Book “Effective Java” by Joshua Block page #11. Google would get you the soft copy of the book for free.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *