·
Product: This is an interface for
creating the objects.
·
ConcreteProduct:This is
a class which implements the Product interface.
·
Creator:This is
an abstract class and declares the factory method, which returns an object of type
Product.
·
ConcreteCreator:This is
a class which implements the Creator class and overrides the factory method to
return an instance of a ConcreteProduct.
Where to use factory:
It would be tedious
when the client needs to specify the class name while creating the objects. So,
to resolve this problem, we can use Factory pattern. It provides the client a
simple way to create the object. The example below will elaborate the factory pattern
in detail.
Ø
Static Factory methods
are common in frameworks where library code needs to create objects of types
which may be sub classed by applications using the
framework.
Ø
Some or all concrete
products can be created in multiple ways, or we want to leave open the option
that in the future there may be new ways to create the concrete product.
Ø
Factory method is used
when Products don't need to know how they are created.
Ø
We can use
factory pattern where we have to create an object of any one
of sub-classes depending on the data provided
Step wise creation
Ø Step 1: Define Product
Ø Step 2: Define Concrete Product
Ø Step 3: Define Creator
Ø Step 4: Define Concrete Creator
Ø Step 5: Define Client
Implimentation
//Step 1: Define Product
abstract class Car
{
public abstract string Title
{ get; }
}
//Step 2: Define Concrete Product
class SportsCar : Car
{
public override string Title
{
get
{
return "Sports
Car";
}
}
}
//Step 2: Define Concrete Product
class Luxury : Car
{
public override string Title
{
get
{
return "Luxury
Car";
}
}
}
//Step 2: Define Concrete Product
class Large : Car
{
public override string Title
{
get
{
return "Large
Car";
}
}
}
//Step 3: Define Creator
abstract class Creator
{
public abstract Car FactoryMethod(CarTypes
carType);
}
enum CarTypes
{
SportsCar,
Luxury,
Large
}
//Step 4: Concrete Creator
class ConcreteCreator
: Creator
{
public override Car
FactoryMethod(CarTypes carType)
{
Car car=null;
switch(carType)
{
case CarTypes.Large:
car= new
Large();
break;
case CarTypes.Luxury:
car= new Luxury();
break;
case CarTypes.SportsCar:
car= new Large();
break;
}
return car;
}
}
No comments:
Post a Comment