Skip to content

Design Pattern: Factory Method

fahimc edited this page Mar 10, 2013 · 2 revisions

Definition

A Factory method requires the factory to create object when requested by the client. The factory will decide which object to create.

##How to ###1.Create an Interface.

var IVehicle=
{
	seats:0,
	wheels:0,
	doors:0,
	info:function(){}
}

###2. Create a Class which implements the Interface

var Vehicle = function(){
	this.info=function()
	{
		var data = "seats: "+this.seats;
		data += ", wheels: "+this.wheels;
		data += ", doors: "+this.doors;
		return data;
	}
}
Class.implement(Vehicle,IVehicle);

###3. Create Two Classes which extend the Vehicle Class

var Car = function(){
	this.seats=4;
	this.wheels=4;
	this.doors=2;
};
Class.extend(Car,Vehicle);
				
var Bike = function(){
	this.seats=1;
	this.wheels=2;
	this.doors=0;
};
Class.extend(Bike,Vehicle);

Now we have two Classes which a the factory can create on demand. Lets create the factory Class

var Factory =
{
	createVehicle:function(type)
	{
		var vehicle;
		switch(type)
		{
		case "Car":
		vehicle = new Car();
		break;
		case "Bike":
		vehicle = new Bike();
		break;
							
		}
						
		return vehicle;
		}
}

The factory will create a vehicle depending on the type.

###4. Test We can now log the info of each create vehicle.

console.log(Factory.createVehicle('Car').info());
console.log(Factory.createVehicle('Bike').info());

Clone this wiki locally