I am implementing the factory method approach. My intention is to know if my approach is correct for factory method. Any modifications to be done to align with the approach?
First I am creating an interface IAuto.
//IAuto.cs
namespace TestDesignPatterns.Auto
{
public interface IAuto
{
void start();
void stop();
}
}
Create a class that implements the IAuto.
//clsBMW.cs
namespace TestDesignPatterns.Auto
{
public class clsBMW : IAuto
{
public void start()
{
Console.WriteLine("BMW started");
}
public void stop()
{
Console.WriteLine("BMW stopped");
}
}
}
Create another concrete class for Audi implementing IAuto.
namespace TestDesignPatterns.Auto
{
public class clsAudi : IAuto
{
public void start()
{
Console.WriteLine("Audi started");
}
public void stop()
{
Console.WriteLine("Audi stopped");
}
}
}
Create an Interface of factory which creates the model.
//IautoFactory.cs
public interface IAutoFactory
{
IAuto createModel(ModelType m);
}
concrete factory class.
//clsAutofactory.cs
public class clsAutoFactory : IAutoFactory
{
public IAuto createModel(ModelType m)
{
IAuto instance = null;
switch (Convert.ToInt32(m))
{
case 0:
instance = new clsBMW();
break;
case 1:
instance = new clsAudi();
break;
default:
break;
}
return instance;
}
}
Main Program
public enum ModelType
{
BMW=0,
Audi=1
}
//program.cs
IAutoFactory factory = new clsAutoFactory();
IAuto model = factory.createModel(ModelType.Audi);
model.start();
model.stop();
Console.ReadKey();