Yes, assuming all four machines' Dispense
and Deposit
methods share the same contract, all you need is to create an interface that they all implement:
public interface IMachine
{
void Dispense();
void Deposit();
}
Then make sure you implement this same interface on all your machine concrete implementations:
public class MachineA : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
public class MachineB : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
public class MachineC : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
public class MachineD : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
I'm assuming you don't use Dependency Injection or have an IoC container currently in your system, so to keep things simple you can have a Factory to always create the IMachine
instances for you:
public static class MachineFactory
{
// this is assuming you are reading the machine name from AppConfig
private static Lazy<string> _machineName = new Lazy<string>(() => ConfigurationManager.AppSettings["TargetMachine"]);
public IMachine GetMachine()
{
switch(_machineName.Value)
{
case "MachineA":
return new MachineA();
break;
case "MachineB":
return new MachineB();
case "MachineC":
return new MachineC();
case "MachineD":
return new MachineD();
}
}
}
Now, in the rest of your application, whenever you need an instance of a machine, all you need to do is use the factory without having to worry about the different machine implementations:
var machine = MachineFactory.GetMachine();