Thursday, May 15, 2008

Factory Pattern

Factory and abstract factory pattern are little confusing but mostly used pattern in object oriented design.

Factory Pattern
The definition of factory pattern in simple "encapsulate object creation" and from Gang of 4 "Define an interface for creating an object but let subclass to decide which class to instantiate".

Here is one example, we have a concrete CarBuilder class implementation and a method buildCar as follows, this class has other important methods to build a car also.

public class CarBuilder {
public void buildCar(String name) {
Car car = null;
if(name.equals("ford") { car = new Ford(); }
if(name.equals("honda") { car = new Honda(); }
if(name.equals("chev") { car = new Chev(); }
assemble(car);
sendToPaint(car);
delivery(car);
}
}

Okay, all are fine, our class is ready to support 3 types car creation and supporting methods. After some days, now we want to add Toyota into this mix, so we need to add one more condition in buildCar method, and after some time we need to add 3 more types and adding 3 more if conditions in code, looks bad as well as we are leading to ambiguous class. So now we have to remove all if conditions to some class like utility class and pass name from here to get correct class implementation. Removing all if condition from here to other class is a simple factory pattern, that is, encapsulate object creation.

public class SimpleCarFactory {
public static Car createCar(Sting name) {
Car car = null;
if(name.equals("ford") {car = new Ford(); }
if(name.equals("honda") { car = new Honda(); }
if(name.equals("chev") { car = new Chev(); }
if(name.equals("toyota") { car = new Toyota(); }
return car;
}
}

createCar method declared static so we can call this method without instantiate SimpleCarFactory class. We haven't really into real factory pattern yet. This is just a starting point.

No comments:

From Generative AI to Agentic AI: 2 Weeks of Building MyNewsAI.io

From Generative to Agentic AI: 2 Weeks Building MyNewsAI.io Over the last two weeks, I set out to evolve MyNewsAI...