Design Pattern - Factory Pattern

Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
The intent of this design pattern is:

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


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. 

Probably the factory pattern is one of the most used patterns.

For example a graphical application works with shapes. In our implementation the drawing framework is the client and the shapes are the products. All the shapes are derived from an abstract shape class (or interface). The Shape class defines the draw and move operations which must be implemented by the concrete shapes. Let's assume a command is selected from the menu to create a new Circle. The framework receives the shape type as a string parameter, it asks the factory to create a new shape sending the parameter received from menu. The factory creates a new circle and returns it to the framework, casted to an abstract shape. Then the framework uses the object as casted to the abstract class without being aware of the concrete object type.



The advantage is obvious: New shapes can be added without changing a single line of code in the framework(the client code that uses the shapes from the factory). As it is shown in the next sections, there are certain factory implementations that allow adding new products without even modifying the factory class.


public class ProductFactory{
 public Product createProduct(String ProductID){
  if (id==ID1)
   return new OneProduct();
  if (id==ID2) return
   return new AnotherProduct();
  ... // so on for the other Ids
  
        return null; //if the id doesn't have any of the expected values
    }
    ...
}

This implementation is the most simple and intuitive (Let's call it noob implementation).
The problem here is that once we add a new concrete product call we should
modify the Factory class. It is not very flexible and it violates open close principle. Of course we can subclass the factory class, but let's not forget that the factory class is usually used as a singleton. Subclassing it means replacing all the factory class references everywhere through the code.

abstract class Product
{
 public abstract Product createProduct();
 ...
}

class OneProduct extends Product
{
 ...
 static
 {
  ProductFactory.instance().registerProduct("ID1", new OneProduct());
 }
 public OneProduct createProduct()
 {
  return new OneProduct();
 }
 ...
}

class ProductFactory
{
 public void registerProduct(String productID, Product p)    {
  m_RegisteredProducts.put(productID, p);
 }

 public Product createProduct(String productID){
  ((Product)m_RegisteredProducts.get(productID)).createProduct();
 }
}
Class Registration - using reflection
If you can use reflection, for example in Java or .NET languages, you can register new product classes to the factory without even changing the factory itself. For creating objects inside the factory class without knowing the object type we keep a map between the productID and the class type of the product. In this case when a new product is added to the application it has to be registered to the factory. This operation doesn't require any change in the factory class code.
class ProductFactory
{
 private HashMap m_RegisteredProducts = new HashMap();
 public void registerProduct (String productID, Class productClass)
 {
  m_RegisteredProducts.put(productID, productClass);
 }
 public Product createProduct(String productID)
 {
  Class productClass = (Class)m_RegisteredProducts.get(productID);
  Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
  return (Product)productConstructor.newInstance(new Object[] { });
 }
}
 
We can put the registration code anywhere in our code, but a convenient place is inside the product class in a static constructor. Look at the example below:
1. Registration done outside of product classes:
public static void main(String args[]){
  Factory.instance().registerProduct("ID1", OneProduct.class);
 }
2. Registration done inside the product classes:
class OneProduct extends Product
{
 static {
  Factory.instance().registerProduct("ID1",OneProduct.class);
 }
 ...
}
We have to make sure that the concrete product classes are loaded before they are required by the factory for registration(if they are not loaded they will not be registered in the factory and createProduct will return null). To ensure it we are going to use the Class.forName method right in the static section of the main class. This section is executed right after the main class is loaded. Class.forName is supposed to return a Class instance of the indicated class. If the class is not loaded by the compiler yet, it will be loaded when the Class.forName is invoked. Consequently the static block in each class will be executed when each class is loaded:
class Main
{
 static
 {
  try
  {
   Class.forName("OneProduct");
   Class.forName("AnotherProduct");
  }
  catch (ClassNotFoundException any)
  {
   any.printStackTrace();
  }
 }
 public static void main(String args[]) throws PhoneCallNotRegisteredException
 {
  ...
 }
}
This reflection implementation has its own drawbacks. The main one is performance. When the reflection is used the performance on code involving reflection can decrease even to 10% of the poerfomance of a non reflection code. Another issue is that not all the programming languages provide reflection mechanism.
Conclusion:

When you design an application just think if you really need it a factory to create
objects. Maybe using it will bring unnecessary complexity in your application. 
If you have many objects of the same base type and you manipulate them 
mostly casted to abstract types, then you need a factory. If you're code should 
have a lot of code like the following, you should reconsider it:

(if (ConcreteProduct)genericProduct typeof )
 ((ConcreteProduct)genericProduct).doSomeConcreteOperation().


Design Pattern - Singleton Pattern

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under the category of creational pattern as this pattern provides one of the best ways to create an object.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

The intent of this design pattern is
  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.




class Singleton
{
private static Singleton instance;
private Singleton()
{
...
}

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();

return instance;
}
...
public void doSomething()
{
...
}
}


You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.

The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:

Singleton.getInstance().doSomething();

Applicability & Examples


According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:


Example 1 - Logger Classes


The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes


The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 - Accessing resources in shared mode


It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 - Factories implemented as Singletons


Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.