Showing posts with label factory pattern. Show all posts
Showing posts with label factory pattern. Show all posts

Saturday, 28 May 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.

Wednesday, 2 March 2011

Iterator Pattern in Java

Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation and places the responsibility where it should be.
One Real time example of Iterator Pattern is the usage of Remote Controls in Home. This example I came accross when I was reading my husband's blog and found very intresting. I will share the same example with you.
Any Remote Control we use to start pressing up and down and back keys to iterate through the channels.

public interface Iterator {
public Channel nextChannel(int currentChannel);
public Channel previousChannel(int currentChannel);
}


The Channel iterator is common for all the remote controls.It's like a specification implemented by all the remote control manufacturing companies.


public class ChannelSurfer implements Iterator{
public Channel nextChannel(int currentChannel) {
Channel channel=new Channel(currentChannel+1);
return channel;
}
public Channel previousChannel(int currentChannel) {
Channel channel=new Channel(currentChannel-1);
return channel;
}
}


public class RemoteControl {
private ChannelSurfer surfer;
public RemoteControl() {
surfer=new ChannelSurfer();
}
public Program getProgram(ChannelSurfer surfer) {
return new Program(surfer.nextChannel());
}
}

public class Program {// ... Some specific implementation of Program class.}
}


We all know that every channel is associated with program and it's basically the program and not the channel number which a user wants to see.This applies that we can apply some logic before returning the elements through iterator.Iterator here can also be programmed to return 'the programs' straight away rather than returning the channels.
Common Java Iterator is Iterator itself.Interface Signature has been copied from the javadoc.
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
-> Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
-> Method names have been improved.

public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}


java.util.Collection interface a root interface in Collections hierarchy contains a method iterator() which returns the Iterator interface.
Hence any class implementing Collection interface should provide definition for iterator() method.But please note that there are no Guarantees concerning the order(unless this collection is an instance of some class that provides a guarantee) as List by definition guarantees ordered Collection.
When we try to view List interface which extends Collection interface it has a method iterator() which returns an Iterator over the elements in this list in proper sequence.
Now coming to ArrayList a subclass class implementing List interface - which also extends AbstractList class provides definition for iterator() method.Infact all the underlying logic sits in AbstractList class.
When we try to view code it tries to return a Itr innerClass object.

public Iterator<E> iterator() {
return new Itr();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}

 

Other Patterns



Composite Pattern
Iterators are often used to recursively traverse composite structures.
Factory Method
Polymorphic iterators use factory methods to instantiate the appropriate iterator subclass.

Sunday, 27 February 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.

Wednesday, 12 January 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.