factory class design pattern code example
Example: simple factory pattern
enum FanType
{
TableFan,
CeilingFan,
ExhaustFan
}
interface IFan
{
void SwitchOn();
void SwitchOff();
}
class TableFan : IFan {.... }
class CeilingFan : IFan {.... }
class ExhaustFan : IFan {..... }
interface IFanFactory
{
IFan CreateFan(FanType type);
}
class FanFactory : IFanFactory
{
public IFan CreateFan(FanType type)
{
switch (type)
{
case FanType.TableFan:
return new TableFan();
case FanType.CeilingFan:
return new CeilingFan();
case FanType.ExhaustFan:
return new ExhaustFan();
default:
return new TableFan();
}
}
}
static void Main(string[] args)
{
IFanFactory simpleFactory = new FanFactory();
IFan fan = simpleFactory.CreateFan(FanType.TableFan);
fan.SwitchOn();
Console.ReadLine();
}