Factory Pattern (Contd.)

Ok. Now Ford, Honda, Toyota coming back to us and saying that you know what, we are no longer a single country car makers, we have multiple car assembly plant, all across globe, we want you to design something to fit into our global assembly model. Oops...what to do? how to improve our design? Here comes real factory model. While we talk with them further, we understood that they are going to use same assemble, sentToPaint and delivery for different countries. One thing definitely going to change is car creation because now we have a simple car factory but the requirement says we need different cars based on different countries.

To achieve the above problem statement, first thing we do is convert CarBuilder class to an abstract class, we no longer use simple parametrize create car factory, we need something robust, multiple factories depends on countries.

Lets think about country based factories like India, US, Japan and so on. So definitely we need a IndiaCarFactory, USCarFactory, JapanCarFactory. Now what we have as a common with in these factories, one thing is assemble,sendToPaint,delivery so does it make sense if we implement all these methods in super class and let sub class implement createCar method and let sub class decide which car object to instantiate depends on country. That's our factory model. Here is real implementation.

public abstract class CarBuilder {
public void assemble(Car car) {
//a concrete shared assemble implementation goes here.
}
public void sendToPaint(Car car) {
//a concrete shared send to paint implementation goes here.
}
public void delivery(Car car) {
//a concrete shared delivery implementation goes here.
}
//this is going to differ based on country
abstract Car createCar(String name);
public void buildCar(String name)
{
Car car = this.createCar(name);
assemble(car);
sendToPaint(car);
delivery(car);
}
}

Here is factory implementation.
public class IndiaCarFactory extends CarBuilder {
Car createCar(String name) {
Car car = null;
if(name.equals("ford") {car = new IndiaFord(); }
if(name.equals("honda") { car = new IndiaHonda(); }
if(name.equals("chev") { car = new IndiaChev(); }
if(name.equals("toyota") { car = new IndiaToyota(); }
return car;
}
}

The same can be implement in USCarFactory and JapanCarFactory etc. So when we want to these from caller, all we need to do is

CarBuilder builder = new IndiaCarFactory();
builder.buildCar("honda");

that's it, now we have a car builder from India factory for Honda.

Comments

Popular posts from this blog

Coupon Crazy

Google's Killer Application.

Uncontrolled Musing