Wednesday, 7 August 2013

Creational Design Patterns -> Factory Pattern

Motivation:
The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. It comes in different variants and implementations. If you are searching for it, most likely, you'll find references about the GoF patterns: Factory Method and Abstract Factory.

In this article we'll describe a flavor of factory pattern commonly used nowdays. You can also check the original Factory Method pattern which is very similar.


Intent:
•    creates objects without exposing the instantiation logic to the client.
•    refers to the newly created object through a common interface

The factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact classof object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implements the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."[1]
Factory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class. In GOF pattern list Factory pattern is listed as Creation design pattern. Factory should be an interface and clients first either creates factory or get factory which later used to create objects.



The implementation is really simple

•    The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
•    The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class).
•    The client uses the products as abstract products without being aware about their concrete implementation.



The factory pattern can be used when:

•    The creation of an object precludes its reuse without significant duplication of code.
•    The creation of an object requires access to information or resources that should not be contained within the composing class.
•    The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
Factory methods are common in toolkits and frameworks, where library code needs to create objects of types that may be subclassed by applications using the framework.

Encapsulation
Factory methods encapsulate the creation of objects. This can be useful, if the creation process is very complex; for example, if it depends on settings in configuration files or on user input.

Consider as an example a program that reads image files. The program supports different image formats, represented by a reader class for each format.
Each time the program reads an image, it needs to create a reader of the appropriate type based on some information in the file. This logic can be encapsulated in a factory method. This approach has also been referred to as the Simple Factory


When to use Factory design pattern in Java

•    Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework.       
•    Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
•    Factory method is used when Products don't need to know how they are created.
•    We  can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided

Advantage of Factory method Pattern in Java:
 
Factory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks.In following are main advantages of using Factory pattern in Java:

1) Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?
E.g.: JDBC is a good example for this pattern; application code doesn't need to know what database it will be used with, so it doesn't know what database-specific driver classes it should use. Instead, it uses factory methods to get Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS specific feature?

2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory.

3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.

4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.

Sources: Wikipedia, OODesign, TutorialsPoint, Javarevisited

Creational Design Patterns -> Singleton Pattern


Motivation:
Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent:
•    Ensure that only one instance of a class is created.
•    Provide a global point of access to the object.

Single Pattern ensures following things.
•    It ensures that instance is created only once.
•    It ensures that instance will never be null.
•    It ensures that instance will be thread safe.
•    Instance uses little memory.
•    Provides lazy instantiation.
•    Class is freezes for sub-classing and instantiation.


Static
Singleton
It has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.

static member classes cannot implement an interface, unless that interface is simply a marker.
if the class has to realize a contract expressed by an interface, it really has to be a singleton.




Usage: classes that basically does conversions,utility functions. please check Math class.
Usage: classes that serve as global configuration , ex: Trial version of software with one database connection, JDK Runtime classes instances per jvm.
helper classes, used by all the classes in your api development.
When to go: 1.While developing your code,you think of forward compatibilty, like tomorrow when you need to convert this singleton class to normal class or allow subclassing. 2. You can provide lazy loading feature , when this singleton class is heavy.
Eager Loading
Lazy loading (requiring no memory or resources until needed)
java.lang.Math 
java.lang.Runtime
Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.
On the other hand, you can override methods defined in Singleton class by extending it.





Lazy initialization:
public class SingletonDemo {
        private static volatile SingletonDemo instance = null;

        private SingletonDemo() {       }

        public static SingletonDemo getInstance() {
                if (instance == null) {
                        synchronized (SingletonDemo .class){
                                if (instance == null) {
                                        instance = new SingletonDemo ();
                                }
                      }
                }
                return instance;
        }
}



Eager initialization:
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}



Enum Way (from Java 5 onwards)
public enum Singleton {
        INSTANCE;
        public void execute (String arg) {
                //... perform operation here ...
        }
}


This approach implements the singleton by taking advantage of Java's guarantee that any enum value is instantiated only once in a Java program. Since Java enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
readResolve()


Examples:
•  Java.lang.Runtime with getRuntime() method
•  Java.awt.Toolkit with getDefaultToolkit()
•  Java.awt.Desktop with  getDesktop()

Note: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

Hot Spot:
•    Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
•    Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
•    Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
•    Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.

Sources: Wikipedia, OODesign, TutorialsPoint, Javarevisited