Monday, July 14, 2008

Factroy Design Pattern

Abstract Factory is commonly known as factory pattern. In this pattern all the classes involved implement/realize the same interface and the compiler only knows that the created object implements the specific interface but not the object's type. This is very flexible when you need to make a creation decision at runtime depending on some aspect of object's behavior rather than it's type.

Example: Imagine that there is a rental store of cars, bikes, trucks, etc but you want to deliver a vehicle depending on the customer's choice.

Programmatically you can make a run time decision using a switch statement to return a new instance of a class which implements the specific interface depending on the customer's choice. As you can see in the constructor of "Journey" class we are getting vehicletype of the current customer and passing it to the VehicleSupplier class's static method "GetVehicle". VehicleSupplier relies on a switch statement to return the vehicle needed, so if you observe here compiler just knows that newly created object implements the "IVehicle" interface but not if it's a car, truck or a bike upfront.

public class Journey

{

public IVehicle rentedVehicle;
public Journey(string customerID)
{
VehicleType vType = Customer.GetVehicleType(customerID);
/*Here is the late binding. Compiler doesn't know the type of the object except that it implements the IVehicle interface*/

rentedVehicle = VehicleSupplier.GetVehicle(vType);

}

//Method for beginning the journey
public void BeginJourney()
{
if (rentedVehicle != null)
{
rentedVehicle.Drive();
}
}
//Method for parking the vehicle
public void ParkTheVehicle()
{
if (rentedVehicle != null)
{
rentedVehicle.Park();
}
}
}
//The class which returns the new vehicle instance depending on the //vehicle type
public class VehicleSupplier
{
public static IVehicle GetVehicle(VehicleType vType)
{
switch (vType)
{
case VehicleType.CAR:
return new Car();
case VehicleType.TRUCK:

return new Truck();
case VehicleType.BIKE:
return new Bike();
}
return null;
}
}
//The interface which will be implemented by Car, Truck and Bike //classes
public interface IVehicle
{
void Drive();
void Park();
}
//enum of the vehicle types
public enum VehicleType{ CAR = 1, TRUCK, BIKE };

Best Regards

No comments: