Showing posts with label Creational Pattern. Show all posts
Showing posts with label Creational Pattern. Show all posts

Saturday, May 28, 2011

Difference between Factory Pattern or Abstract Factory Pattern and Builder Pattern

Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction.

Both are creational pattern but differ:
Factory Pattern Builder Pattern
The factor pattern defers the choice of what concrete type of object to
make until run time.
E.g. going to a restaurant to order the special of  the day.  The waiter is the interface to the factory that takes the
abstractor generic message "Get me the special of the day!" and returns
the concrete product (i.e "Chilli Paneer" or some other dish.)
The builder pattern encapsulates the logic of how to put together a
complex object so that the client just requests a configuration and the
builder directs the logic of building it.   E.g The main contractor
(builder) in building a house knows, given a floor plan, knows how to
execute the sequence of operations (i,e. by delegating to subcontractors)
needed to build the complex object.  If that logic was not encapsulated in
a builder, then the buyers would have to organize the subcontracting
themselves 
The factory is concerned with what is made. The builder with how it is
made. So it focuses on the steps of constructing the complex object.
In case of Factory or Abstract Factory, the product gets returned immediately Builder returns the product as
the final step.

Thursday, May 19, 2011

Builder pattern

Builder pattern is used to construct a complex object step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.

For example, you can consider construction of a home. Home is the final end product (object) that is to be returned as the output of the construction process. It will have many steps, like basement construction, wall construction and so on roof construction. Finally the whole home object is returned. Here using the same process you can build houses with different properties.

GOF says,
“Separate the construction of a complex object from its representation so that the same construction process can create different representations” [GoF 94]

Sample builder design pattern implementation in Java API

DocumentBuilderFactory , StringBuffer, StringBuilder are some examples of builder pattern usage in java API.

Components in Builder Pattern:

Builder
Abstract interface for creating objects (product).

Concrete Builder
Provide implementation for Builder. Construct and assemble parts to build the objects.

Director
The Director class is responsible for managing the correct sequence of object creation. It receives a Concrete Builder as a parameter and executes the necessary operations on it.

Product
The final object that will be created by the Director using Builder.

Builder Pattern and other Creational Patterns
Unlike creational patterns that construct products in one shot,the builder pattern constructs the product step by step.

Sometimes creational patterns are complementary.Builder can use one of the other patterns to implement which components get built.Abstract Factory,Builder,and Prototype can use Singleton in their implementations.[GoF,p81,134]

Builder focuses on constructing a complex object step by step.Abstract Factory emphasizes a family of product objects(either simple or complex).Builder returns the product as a final step,but as far as the Abstract Factory is concerned,the product gets returned immediately.[GoF,p105]. See - Difference between abstract factory pattern and builder pattern.

Builder often builds a composite[GoF,p106]

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. 

Sample Java Source Code for Builder Pattern

Let us look at an example

/** "Product" */
class HolidayPackage {
private String flightBookingRef = "";
private String carBookingRef = "";
private String hotelBookingRef = "";

//setters and getters

}

/** "Abstract Builder" */
abstract class HolidayPackageBuilder {

protected HolidayPackage holidayPackage;

public HolidayPackageBuilder(){
holidayPackage = new HolidayPackage();
}

public abstract void build();

}


/** "ConcreteBuilder" */
public class BookCarBuilder extends HolidayPackageBuilder {

public void build(){
bookCar();
}

private void bookCar() {
String carBookingRef = null;

// functionality to book the car and
// get the ref and assign it to carBookingRef
// let us give some hard coded value to carBookingRef

carBookingRef = "SPC3778/09";

holidayPackage.setCarBookingRef(carBookingRef);

System.out.println("Car has been successfully booked - "+carBookingRef);
}


}

class BookFlightBuilder extends HolidayPackageBuilder {

public void build(){
bookFlight();
}

private void bookFlight() {
String flightBookingRef = null;

// functionality to book the flight and
// get the ref and assign it to flightBookingRef
// let us give some hard coded value to flightBooking Ref

flightBookingRef = "SPF3778/09";

holidayPackage.setFlightBookingRef(flightBookingRef);

System.out.println("Flight has been successfully booked - "+flightBookingRef);
}

}

public class BookHotelBuilder extends HolidayPackageBuilder {

public void build(){
bookHotel();
}

private void bookHotel() {
String hotelBookingRef = null;

// functionality to book the hotel and
// get the ref and assign it to hotelBookingRef
// let us give some hard coded value to hotelBookingRef

hotelBookingRef = "SPH3778/09";

holidayPackage.setHotelBookingRef(hotelBookingRef);

System.out.println("Hotel has been successfully booked - "+hotelBookingRef);
}

}

public class ConcreteHolidayPackageBuilder extends HolidayPackageBuilder {

BookFlightBuilder bookFlightBuilder;
BookCarBuilder bookCarBuilder;
BookHotelBuilder bookHotelBuilder;

public ConcreteHolidayPackageBuilder(){
bookFlightBuilder = new BookFlightBuilder();
bookCarBuilder = new BookCarBuilder();
bookHotelBuilder = new BookHotelBuilder();
}

public void build(){
bookCompletePackage();
}

private void bookCompletePackage() {
bookFlightBuilder.build();
bookCarBuilder.build();
bookHotelBuilder.build();
}


}



/** "Director" */
class HolidayPackageReader {

private HolidayPackageBuilder holidayPackageBuilder;

public void setHolidayPackageBuilder(HolidayPackageBuilder holidayPackageBuilder){
this.holidayPackageBuilder = holidayPackageBuilder;
}


public void build() {
holidayPackageBuilder.build();
}
}



public class BuilderPatternDemo {

public static void main(String[] args) {

// You can book the complete package or book them seperately also.
HolidayPackageBuilder builder = new ConcreteHolidayPackageBuilder();

HolidayPackageReader packageReader = new HolidayPackageReader();
packageReader.setHolidayPackageBuilder(builder);

packageReader.build();

}
}

Advantages :
1. Encapsulate the way a complex object is constructed.
2. Allows objects to be constructed in a multistep and varying processes.
3. Hides the internal representation of the product from the client.
4. Product implementation can be swapped in and out because the client only sees the abstract interface.


Disadvantages:
1. Often used for building complex structures.
2. Constructing objects requires more domain knowledge of the client than when using a factory.

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

Creational Patterns in java

This Design pattern is all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done. Following are the patterns under this category:





Sunday, February 27, 2011

Abstract factory pattern

This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the subclasses.
Let’s understand this pattern with the help of an example.
Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for.
The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server.
So, here we have an abstract base class Computer.

 

package creational.abstractfactory; 

public abstract class Computer {

public abstract Parts getRAM();
public abstract Parts getProcessor();
public abstract Parts getMonitor();

}




This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Let’s have a look at the class Parts.



package creational.abstractfactory; 
public class Parts {

public String specification;
public Parts(String specification) {
this.specification = specification;
}

public String getSpecification() {
return specification;
}

}// End of class




And now lets go to the sub-classes of Computer. They are PC, Workstation and Server.



package creational.abstractfactory; 
public class PC extends Computer {

public Parts getRAM() {
return new Parts("512 MB");
}
public Parts getProcessor() {
return new Parts("Celeron");
}

public Parts getMonitor() {
return new Parts("15 inches");
}
}




package creational.abstractfactory;

public class Workstation extends Computer {

public Parts getRAM() {
return new Parts("1 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 3");
}

public Parts getMonitor() {
return new Parts("19 inches");
}
}




package creational.abstractfactory; 
public class Server extends Computer{

public Parts getRAM() {
return new Parts("4 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 4");
}

public Parts getMonitor() {
return new Parts("17 inches");
}
}




Now let’s have a look at the Abstract factory which returns a factory “Computer”. We call the class ComputerType.

package creational.abstractfactory;
public class ComputerType {
private Computer comp; public static void main(String[] args) {
ComputerType type = new ComputerType(); Computer computer = type.getComputer("Server");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
}

public Computer getComputer(String computerType) {
if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
else if(computerType.equals("Server"))
comp = new Server(); return comp;

}
}




Running this class gives the output as this:
Monitor: 17 inches
RAM: 4 GB
Processor: Intel P 4.

 

When to use Abstract Factory Pattern?
One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.

Factory pattern

Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.
Let’s take an example to understand this pattern.
The Base class

public class Person {
// name string
public String name;
// gender : M or F
private String gender;

public String getName() {
return name;
}

public String getGender() {
return gender;
}
}// End of class
This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen.
Male.java

public class Male extends Person {
public Male(String fullName) {
System.out.println("Hello Mr. "+fullName);
}
}// End of class
Also, the class Female

public class Female extends Person {
public Female(String fullNname) {
System.out.println("Hello Ms. "+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided.


public class SalutationFactory {
public Person getPerson(String name, String gender) {
if (gender.equals("M"))
return new Male(name);
else if(gender.equals("F"))
return new Female(name);
else return null;
}
}// End of class


This class accepts two arguments from the system at runtime and prints the names.

Running the program:
FactoryPatternDemo.java


public class FactoryPatternDemo{
public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson("Kinshuk", "M");
}
}

The result returned is:

“Hello Mr. Kinshuk”.

When to use a Factory Pattern?


The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. 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.




Download source


You can download the source code of this program from here.

Saturday, February 26, 2011

Singleton pattern

Step 1: Provide a default Private constructor
public class Singleton {

// Note that the constructor is private
private Singleton() {
// Optional Code
}
}
Step 2: Create a Static Method for getting the reference to the Singleton Object
public class Singleton {

private static Singleton instance;
// Note that the constructor is private
private Singleton() {
// Optional Code
}
public static Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized Singleton getInstance()
It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class Singleton {

private static Singleton singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private Singleton() {
// Optional Code
}
public static synchronized Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
// Singleton obj = new Singleton(); //Compilation error not allowed 
Singleton obj = Singleton.getInstance();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}



Another approach
We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass {

private static Singleton ourInstance = new Singleton();
public static SingletonClass getInstance() {
return singletonObj;
}
private SingletonClass() {
}
}
In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the class when the application is running.

But still there are some issues left.
Protected vs Private Constructor 
protected Singleton() {
// ...
}
The constructor could be made private to prevent others from instantiating 
this class. But this would also make it impossible to create instances of 
Singleton subclasses.
 

Wednesday, January 12, 2011

Factory pattern example in java

If you want to read about factory pattern, please refer this link - Factory Pattern.

Consider the following Button class, which has a single draw() method. Since this class is a generic class, we have made it as abstract.
Button.java

package tips.pattern.factory;

public abstract class Button {

public abstract void draw();

}

Given below are the concrete implementations of the Button class, WindowsButton and LinuxButton, each providing a much simplified implementation for the draw() method.
WindowsButton.java

package tips.pattern.factory;

public class WindowsButton extends Button{

@Override
public void draw() {
System.out.println("Drawing Windows Button");
}

}
LinuxButton.java

package tips.pattern.factory;

public class LinuxButton extends Button{

@Override
public void draw() {
System.out.println("Drawing Linux Button");
}

}

Now let us come to the core implementation, the Factory class itself. The ButtonFactory class has one static method called createButton() which the clients can invoke to get the Button object. Note the return type of the method, it is neither WindowsButton nor LinuxButton, but the super type of the both, i.e, Button. Whether the return type of method is WindowsButton or LinuxButton is decided based on the input operating system.
ButtonFactory.java

package tips.pattern.factory;

public class ButtonFactory {

public static Button createButton(String os){
if (os.equals("Windows")){
return new WindowsButton();
}else if (os.equals("Linux")){
return new LinuxButton();
}
return null;
}
}

Given below is the client Application that makes use of the above ButtonFactory class. The client is un-aware of the fact there is multiple implementations of the Button class. It accesses the draw() operation through a single unified type Button.
FactoryClient.java

package tips.pattern.factory;

public class FactoryClient {

public static void main(String[] args) {
Button windowsButton =
ButtonFactory.createButton("Windows");
windowsButton.draw();

Button linuxButton =
ButtonFactory.createButton("Linux");
linuxButton.draw();
}
}

So it is clear, that factory class fetches the client the corresponding class depending on the information provided by the client.