hi,
Another post, another pattern !!!!
Scenario :
My good old car racing game. But now the car models have been decided. now i would like to use an Audi and a Benz. So we have a ICar interface which is implemented by two car classes - Audi and Benz.but when i haev to create an instance of the Car class, i will have to pass the car model as parameter. the code will be somewhat like :
if(CarModel == ECarModel.AUDI) // ECarModel is an enum
{
return new Audi();
}
else if(CarModel ==ECarModel.BENZ)
{
return new Benz();
}
This code will be used whenever i want to create an instance of a car. i would create a instance of car for many scenarios like : car upgrade, new car bought, new car won as an award etc. so i will have to replicate this code snippet everywhere. now i want to enhance my game i want to include a few more models like Diablo. Does it mean i have to change the code snippet where ever it is present? yes, of course,i will have to do it. hey , what if i make changes to the existing design itself so that i can accomodate any future enhancements? yes, i need to do it. HOW? i will introduce a new class which deals with creating instances for the cars. this class will be called as CarFactory. it deals only with creating instances of Car class- that is the only purpose of the class. so next time any new car is introduced, i need to change this factory class.
Code is as given below :
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryPattern
{
public interface ICar
{
//some methods for the car like move(),break(),spo(),increaseGear(),DecreaseGear() here
}
class Audi : ICar
{
public Audi()
{
}
//implemnt the interface here
}
class Benz : ICar
{
public Benz()
{
}
//implemnt the interface here
}
public class CarFactory
{
public CarFactory()
{
}
public ICar createCar(string Cartype) // instead of a string i can also pass an enum here
{
if (Cartype == "Audi")
{
return new Audi();
}
if (Cartype == "benz")
{
return new Benz();
}
else
return null;
}
}
}
this is the factory pattern!!! the responsibility of creating the class is handed over to the factory for that class.
Happy coding !!!
No comments:
Post a Comment