Thursday, 19 May 2011

Factory Method Pattern

Definition

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.

Explanation

Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Example

Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

When to use a Factory Pattern?

  • The Factory patterns can be used in following cases:
    When a class does not know which class of objects it must create.
  • A class specifies its sub-classes to specify which objects to create.
  • In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.

UML of Factory-method Pattern

The UML class diagram above describes an implementation of the factory method design pattern.
Factory Method Pattern
Factory Method Pattern UML


Participants in Factory-method pattern

In the diagram above, there are four classes:
  • IFactory: This is an abstract base class or interface for the concrete factory classes that will actually generate new objects.
  • ConcreateFactory: Inheriting from the FactoryBase class, the concreate factory classes inherit the actual factory method. This is overridden with the object generation code unless already implemented in full in the base class.
  • IProduct: This abstract class is the base class or interface for the types of object that the factory can create. It is also the return type for the factory method. Again, this can be a simple interface info general functionality is to be inherited by its subclasses.
  • ConcreateProduct: Multiple subclasses of the Product class are defined, each containing specific functionality. Object of these classes are generated by the factory method.

Example Code in java

Factory and its implementation
interface  IFactory
{
public Product factoryMethod(int type);
}

public class ConcreteFactory implements IFactory
{
@Override
public Product factoryMethod(int type)
{
switch (type)
{
case 1:
return new ConcreteProduct1();

case 2:
return new ConcreteProduct2();

default:
throw new ArgumentException("Invalid type.", "type");
}
}
}
Product class
interface class  IProduct { }

public class ConcreteProduct1 implements IProduct { }

public class ConcreteProduct2 implements IProduct { }
Testing the program
public class  FactoryMethodDemo
{
public static void main(String[] args)
{
IFactory myFactory = new ConcreteFactory();
ConcreteProduct1 product1;
//create product1 from factory
product1 = myFactory.factoryMethod(1);
ConcreteProduct2 product2;
//create product2 from factory
product2 = myFactory2.factoryMethod(2);
}
}

Advantage of Factory-method pattern

  • Eliminates the need to bind application-specific classes into your code
  • Provides hooks for subclassing. Creating objects inside a class with a factory method is always more flexible than creating an object directly. This method gives subclasses a hook for providing an extended version of an object
  • Connects parallel heirarchies. Factory method localises knowledge of which classes belong together. Parallel class heirarchies result when a class delegates some of its responsibilities to a separate class.

Disadvantage of Factory-method pattern


  • Clients might have to subclass the Creator class just to create a particular Concreate object.

Prototype pattern

Prototype Pattern allows you to make new instances by copying the existing instances.

Key aspect of this pattern is that the client code can make new instances without knowing which specific class is being instantiate.

When to use Prototype Pattern?

  1. Use Prototype Pattern when creating an instance of a given class is either expensive or complicated (or) when a system must create new objects of many types in a complex class hierarchy.
  2. When there are many subclasses that differ only in the kind of objects, A system needs independent of how its objects are created, composed, and represented.

Rather than creating more instances,you make copies of the original instance,modifying them as appropriate.
Prototypes can also be used whenever we need classes that differ only in the type of processing they offer,for example in parsing of strings representating numbers in diff radixes.In this sense prototype is nearly the same as Examplar pattern described in Coplien[1992].

Prototype Pattern vs Other patterns

Prototype pattern may look similar to builder design pattern. There is a huge difference to it. If you remember, “the same construction process can create different representations” is the key in builder pattern. But not in the case of prototype pattern.

How to implement Prototype Pattern

You just have to copy the existing instance in hand. When you say copy in java, immediately cloning comes into picture. Thats why when you read about prototype pattern, all the literature invariably refers java cloning.

"Copy Constructor" is one form of Prototype pattern.

Simple way is, clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need. Therefore whenever you clone that object you will directly get the new object of desire without modifying the created object explicitly.

The prototype design pattern mandates that the instance which you are going to copy should provide the copying feature. It should not be done by an external utility or provider.

But the above, other way comes with a caution. If somebody who is not aware of your tweaking the clone business logic uses it, he will be in issue. Since what he has in hand is not the exact clone. You can go for a custom method which calls the clone internally and then modifies it according to the need. Which will be a better approach.

Always remember while using clone to copy, whether you need a shallow copy or deep copy. Decide based on your business needs. If you need a deep copy, you can use serialization as a hack to get the deep copy done. Using clone to copy is entirey a design decision while implementing the prototype design pattern. Clone is not a mandatory choice for prototype pattern.

In prototype pattern, you should always make sure that you are well knowledgeable about the data of the object that is to be cloned. Also make sure that instance allows you to make changes to the data. If not, after cloning you will not be able to make required changes to get the new required object.

Example

Let's consider the case of an extensive database where we need to make a number of queries to construct an answer.Once we have this answer as a table or ResultSet,we might like to manipulate it to produce other answers without issuing additional queries.

Participants in Prototype design

Prototype: Declares an interface for cloning itself.
Concrete Prototype: Implements an operation for cloning itself.
Client: Creates a new object by asking a prototype to clone itself.
We would lose the advantage of Polymorphism that the GoF formulation of the Prototype pattern gives you. - NatPryce.
Prototype means making a clone.This implies cloning of an object to avoid creation.If the cost of creating a new object is large and creation is resource intensive,we clone the object.We use the interface Cloneable and call its method clone() to clone the object.
One thing we cannot use the clone as it is.We need to instantiate the clone before using it.This can be a performance drawback.This also gives sufficient access to the data and methods of the class.This means that data access methods have to be added to the protoype once it has been cloned.
Alternative To the Flyweight pattern is prototype pattern which allows polymorphic copies of existing objects.The object clone() method signature provides support for Prototype pattern.

Prototypes are useful when object initialization is expensive,and you anticipate few variations on the initialization parameters.Then we could keep already-initialized objects in a table,and clone an exisiting object instead of expensively creating a new one from scratch.
Immutable objects can be returned directly when using Prototyping,avoiding the copying overhead.
Recall,that the idea of prototype is that we are passed an object and use that object as a template to create a new object and use that object as a template to create a new object.Because we might not know the implementation details of the object,we cannot create a new instance of the object and copy all of its data.(Some of the data may not be accessible via methods.) So we ask the object itself to give a copy of itself.

Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern.If we have an object that is Cloneable,we can call its clone() method to create a new Instance of the object with the same values.

Note that,Cloneable is a marker interface.It merely acts as a tag to state that we really want instance of the class to be cloned. If we don't implement Cloneable,the super.clone() method will throw CloneNotSupportedException.
The object implementation of clone() performs a shallow copy of the object in question.That is,it copies the values of the fields in the object,but not any actual objects that may be pointed to.In other words,the new object will point to the same objects the old object pointed to.

clone() method always retuns an object of type Object.we must cast it to the actual type of the object we are cloning.There are other significant restrictions on the clone method. See here for restrictions.

Please remember clone() method is a shallow copy of the original class.In other words,references of the data objects are copies,but they refer to the same underlying data.Thus any operation we perform on the copied data will also occur on the original data in the Prototype class.
In some cases,this shallow copy is acceptable,but if you want to make a deep copy of the data ,there is a clever trick using the serializable interface.A class is said to be serializable,if we can write it out as a stream of bytes and read those bytes back in to reconstruct the class.This is how RMI is implemented.

Example code for Prototype Pattern in java

Interface:

public interface Cloneable {
public Object clone();
}

 

Concrete Implementation of Cloneable:

I am providing only name and manufacturer for car, to make it simple. There can be other attributes as well like price, engine etc.

public class Car implements Cloneable {

private final String name;
private final String manufacturer;

public Car(String name, String manufacturer) {
this.name = name;
this.manufacturer= manufacturer;
}

@Override
public Object clone() {
Car clone = new Car(name, manufacturer);
return clone;
}

public String getName() {
return name;
}

public String getManufacturer() {
return manufacturer;
}

}



 

Using the Prototype pattern:

 


public class PrototypeMain {

public static void main(String[] args) {
// Let make maruti suzuki
Car marutiSuzuki=new Car("1000","Maruti Suzuki");
Car audiQuattro = new Car("Quattro","Audi");
// We can add more but let's stop here.
//Let's do pattern and not cars :)
//Lets gift our Audi clone to some fried :P
Car clone = (Car) audi.clone();

if (clone.getManufacturer() == "Audi") {
System.out.println("Thanks to Prototype Pattern");
}
}
}





Advantages of Prototype Pattern



  • Adding and removing products at runtime.

  • Specifying new objects by varying values.

  • Specifying new objects by varying structure.

  • Reduced subclassing.

  • Configure an application with classes dynamically.

  • Hides the complexities of making new instances from the client.

  • Provides the option for the client to generate objects whose type is unknown.

  • In some circumstances,copying an object is more efficient than creating a new object.

Consequences of Prototype Pattern



  • Classes that have circular references to other classes cannot really be cloned.

  • One Difficulty in implementing the Prototype Pattern in Java is that if the classes already exist,we may not be able to change them to add the required clone or deepClone methods.The deepClone() method can be difficult if all the class objects contained in the class cannot be declared to implement Serializable.

  • Finally idea of having prototype classes to copy implies that we have sufficient access to the data or methods to these prototype classes so that we can modify the data once we have cloned the class.

Disadvantages


Drawback to using the Prototype is that making a copy of an object can sometimes be complicated.

Object Pool pattern

Intent

  • Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Problem

  • Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.
  • It is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the Reusable Pool class is designed to be a singleton class.
Caution
Object pooling in java is often seen as an anti pattern and/or wasted effort - but there are still valid reasons to think about pooling for certain kind of applications.
The JVM allocates objects much faster from managed heap (young generation; contiguous and defragmented) as you could ever recycle objects from a self written pool running on top of a VM. A good configured garbage collector is also able to delete unused objects fast. GCs in fact don't delete objects explicitly, they rather evacuate all surviving objects and sweep whole memory regions in a very efficient manner and only when its necessary to reduce runtime overhead.
Object allocation (of small objects) on modern JVMs is even so fast that making a copy of immutable objects sometimes outperforms modification of mutable (and often old) objects. JVM languages like scala or clojure make heavy use of this observation. One of the reasons for that anomaly is that generational JVMs are designed to be able to deal with loads of short living objects which makes them inexpensive compared to long living objects in old generations.

Performance does not always mean Throughput

Rendering a game with 60fps might be optimal throughput for a renderer but the performance might be still unacceptable when all frames are rendered in the first half of the second with the second half spent on GC ;). Even if Object Pools may not increase system throughput they can still increase determinism of your application. Here are some observations and tips which might help:

When should I consider Object Pools?

  • GC tuning did not help - you want to try something else
  • The application creates a lot of objects which die in the old generation
  • Your Objects are expansive to create but easy to recycle
  • Determinism, e.g response time (soft real time requirements) is more important for you than throughput

Pro Pooling:

  • pools reduce GC activity in peak times (worst case scenarios)
  • are easy to implement and test (its basically an array ;))
  • are easy to disable (inject a fake pool which returns only new Objects)

Con Pooling:

  • more (old) objects are referenced when a GC kicks in (increases gc overhead)
  • memory leaks (don't forget to reclaim your objects!)
  • cause additional problems in a multi-threaded scenario (new Object() is thread safe!)
  • may decrease throughput
  • cumbersome, repetitive client code
When you decided to use pools you have to make sure to reclaim all objects as soon they are no longer used. One way of doing this is by applying the static factory method pattern for object allocation and a per object dispose method for deallocation.

Example

to be added soon

Design Principles

The principles of design include following:
Open Close principle
Dependency interversion principle
Interface segregation principle
Single responsibility principle
Liskov's Substitution principle
Principle of least knowledge

These all principles help us manage dependencies and coupling among the software modules in a better way. These principles expose the dependency management aspects of OOD as opposed to the conceptualization and modeling aspects. This is not to say that OO is a poor tool for conceptualization of the problem space, or that it is not a good venue for creating models. Certainly many people get value out of these aspects of OO. The principles, however, focus very tightly on dependency management.

Dependency Management is an issue that most of us have faced. Whenever we bring up on our screens a nasty batch of tangled legacy code, we are experiencing the results of poor dependency management. Poor dependency managment leads to code that is hard to change, fragile, and non-reusable. On the other hand, when dependencies are well managed, the code remains flexible, robust, and reusable. So dependency management, and therefore these principles, are at the foudation of the -ilities that software developers desire.

The first five principles are principles of class design. They are:

SRP The Single Responsibility Principle A class should have one, and only one, reason to change.
OCP The Open Closed Principle You should be able to extend a classes behavior, without modifying it.
LSP The Liskov Substitution Principle Derived classes must be substitutable for their base classes.
DIP The Dependency Inversion Principle Depend on abstractions, not on concretions.
ISP The Interface Segregation Principle Make fine grained interfaces that are client specific.

The above 5 principles are called SOLID, derived from their first name.

Principle of least knowledge or Law of Demeter (LOD)

The principle states: Each unit should only talk to its friends; Don’t talk to strangers. A method of an object should invoke only the methods of the following kinds of objects:
    1. itself 2. its parameters 3. any objects it creates/instantiates 4. its direct component objects

Violation of above principle

Below is an example of some code breaking this principle:
Interface : IOrderManager

public interface IOrderManager
{
void AddItemToOrder(IItem item);
void RemoveItemFromOrder(IItem item);
void ChangeItemName(IItem item, string name);
}


Interface: IItem


public interface IItem
{
int Id { get; set; }
string Name { get; set; }
}

Class: Item : IItem

public class Item : IItem
{
private int _Id;
private string _Name;

public int Id
{
get { return _Id; }
set { _Id = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
Class :OrderManager : IOrderManager

public class OrderManager implements IOrderManager
{
private IOrder _Order;

public OrderManager()
{
_Order = new Order();
_Order.Items = new List<IItem>();
}

public void AddItemToOrder(IItem item)
{
if (_Order.Items != null)
{
if ( ! _Order.Items.Contains(item))
{
_Order.Items.Add(item);
}
}
}
public void RemoveItemFromOrder(IItem item)
{
if (_Order.Items != null)
{
if (_Order.Items.Contains(item))
{
_Order.Items.Remove(item);
}
}
}
public void ChangeItemName(IItem item, string name)
{
if (_Order.Items != null)
{
if (_Order.Items.Contains(item))
{
_Order.Items[_Order.Items.IndexOf(item)].Name = name;
}
}
}

In the above example the OrderManager has the responsibility of adding and removing Items to and from the List collection in the Order class, and even worse it has the responsibility of changing the name of a particular Item inside that collection. This tightly couples the OrderManager to the Order and Item class, if we would change how the Order class is maintaining her Items than we automatically have to change the OrderManager class. The Order should be responsible for its Items, not the OrderManager. Below is the Law Of Demeter implementation of this example:
Interface: IOrder



public interface IOrder
{
void AddItem(IItem item);
void RemoveItem(IItem item);
void ChangeItemName(IItem item, string name);
}


Class: Order : IOrder


public class Order implements IOrder
{
private List<IItem> _Items;

public Order()
{
_Items = new List<IItem>();
}

public void AddItem(IItem item)
{
if (_Items != null)
{
if (!_Items.Contains(item))
{
_Items.Add(item);
}
}
}
public void RemoveItem(IItem item)
{
if (_Items != null)
{
if (_Items.Contains(item))
{
_Items.Remove(item);
}
}
}
public void ChangeItemName(IItem item, string name)
{
if (_Items != null)
{
if (_Items.Contains(item))
{
_Items[_Items.IndexOf(item)].Name = name;
}
}
}
}

Class: OrderManager : IOrderManager


public class OrderManager implements IOrderManager
{
private IOrder _Order;

public OrderManager()
{
_Order = new Order();
}

public void AddItemToOrder(IItem item)
{
_Order.AddItem(item);
}
public void RemoveItemFromOrder(IItem item)
{
_Order.RemoveItem(item);
}
public void ChangeItemName(IItem item, string name)
{
_Order.ChangeItemName(item, name);
}
}

Now we can change how the Order class is keeping its Items without having to change the OrderManager. One nice rule of thumb is: One dot should be enough.

Liskov's Substitution Principle(LSP)

The Liskov’s Substitution Principle provides a guideline to sub-typing any existing type. It is L in SOLID principles.

Definition
 If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behaviour of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

Here is an easier version:
Functions or methods that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
While checking for specific types is technically a violation of LSP, it's more commonly thought of as an OCP violation. LSP is more focused on the behavior of the specific instance itself, rather than types operating upon the specific instance. Below is an example of some code breaking this principle:

Example:
Example1
Violation of LSP - Consider the case of Rectangle and Square problem.

Right way to handle solve this problem - Solution to rectangle square problem.


Summary
This principle is just an extension of the Open Close Principle and it means that we must make sure that new derived classes are extending the base classes without changing their behavior.

Interface Segregation Principle (ISP)

The interface-segregation principle is one of the five SOLID principles of Object-Oriented Design.


Definition
Formally stated, the ISP reads:
Many specific interfaces are better than a single general interface.


Need
Couple of times, we see that we are bound to implement interfaces which are fat, what I mean is we have to implement the methods which we really don't need or would be of any help to us.

This coding tip explains how we can really identify a fat interface and refactor the code in order to make the interface thin without really breaking the application.


Example
Why is this? Look at the following example. Imagine that in your application you are required to write some Data Access Objects (DAO). These data objects should support a variety of data sources. Let's consider that the two main data sources are file and database. You must be careful enough to come up with an interface-based design, where the implementation of data access can be varied without affecting the client code using your DAO object. The following design is a good example of the above requirements (figure below).



There's another aspect that needs be to considered. What happens if the data source is read-only? The methods for inserting and updating data are not needed. On the other hand, if the DAO object should implement the DAO interface, it will have to provide a null implementation for those methods defined in the interface. This is still acceptable, but the design is gradually going wrong. What if there is a need to rotate the file data source to a different file once a certain amount of data has been written to the file? That will require a separate method to add to the DAO interface. This is just to add the flexibility to the clients using this FileDAO object to enable them to choose either the normal append feature to the file data source or to make use of the improved file rotation feature.
With the DatabaseDAO implementation now broken, we'll need to change it, to provide a null implementation of the new method added to the interface. This is against the Open-Closed Principle.
So, what went wrong? In the basic design, the fact that the file data access operation and database access operation can differ fundamentally must be considered. We defined the behaviors for both the data access operation, and the database access operation together in a single interface. This caused problems at a later stage in the development. It is not necessary to be a guru in Object Oriented System Design, to solve this problem nor is vast experience in designing software applications needed. What is necessary is to think of interfaces as the behaviors to be provided through particular objects. If two or more objects implementing the interface depict different sets of behaviors, then they probably cannot subscribe to a single interface.
When a single interface is designed to support different groups of behaviors, they are, by virtue, inherently poorly designed, and are called Fat interfaces. They are called Fat because they grow enormously with each additional function required by clients using that interface.
Thus, for the problem with the Data Access Objects, follow the Interface Segregation Principle, and separate the interfaces based on the behaviors. The database access classes and file access classes should subscribe to two separate interfaces. The following design is obtained by applying the Interface Segregation Principle (Figure below).
 
With this design, the Fat interface symptom is avoided and the interfaces clearly delineate their intended purpose. If any imaginary data access object requires a combination of operations defined in both of these interfaces, they will be able to do so by implementing both the interfaces.

I think the key is if you find yourself creating interfaces that don’t get fully implemented in its clients, then that’s a good sign that you’re violating the ISP. You can check out the link to this pdf for more complete information on the subject.