I am implementing a factory pattern and would like to get it confirmed that it is the right approach. Is there any error in this approach. If so where should i be making the changes.
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
//program.cs
IAutoFactory factory = new clsAutoFactory();
IAuto model = factory.createModel(ModelType.Audi);
model.start();
model.stop();
Console.ReadKey()
Aucun commentaire:
Enregistrer un commentaire