Thursday, January 13, 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.

No comments:

Post a Comment

Chitika