Skip to content

Instantly share code, notes, and snippets.

@pedroreys
Created May 16, 2018 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedroreys/d736515ebf388862fbbc326056df574e to your computer and use it in GitHub Desktop.
Save pedroreys/d736515ebf388862fbbc326056df574e to your computer and use it in GitHub Desktop.

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment