Search code examples
c#design-patternsinterfaceprototype-pattern

Prototype Pattern, why do I need an interface?


I'm playing around with design patterns, and at the moment I'm working with the prototype pattern. The pattern made me wonder, why do I need an interface for this pattern, can't I achieve the same functionality without an interface?

I have created two examples, can anyone explain me why I need the interface?

Interface example:

This is my interface class:

interface IWeapon
{
    IWeapon Clone();
}

My concrete class:

class Rifle : IWeapon
{

    public IWeapon Clone()
    {
        return (IWeapon)this.MemberwiseClone();
    }

}

The Cloning process

 //Create rifle
 Rifle rifle = new Rifle();
 rifle.Name = "M4A1";
 rifle.Rounds = 30;

 //Copy Rifle
 Rifle rifleCopy = (Rifle)rifle.Clone();

This is how I clone without an interface

public Rifle Clone()
{
   return (Rifle)this.MemberwiseClone();
}

Can someone explain me the advantages of using the implementation with the interface over the one without an interface?


Solution

  • Interfaces are great when you have classes that do the same thing, but use different methods to achieve it.

    Using your example, lets say we have something like this...

    public interface ILongRangeWeapon
    {
        void Fire();
    }
    

    Now, lets say you have these classes...

    public class Rifle : ILongRangeWeapon
    {
        public void Fire()
        {
            // Pull the trigger
        }
    }
    
    public class NuclearMissile : ILongRangeWeapon
    {
        public void Fire()
        {
            // Press the red button
        }
    }
    

    Now you can use ILongRangeWeapon in your code, and it doesn't matter which mechanism it uses to fire, it just knows that it CAN fire.

    A more practical application would be connecting to the internet. There are multiple ways to connect, modem, lan, wifi, etc. However, you just don't even care HOW the instance connects, you just want it to connect.

    There are some purists that say you should make everything an interface. I think it adds complexity where it isn't needed just for the sake of adding complexity. It's up to you as a developer to decide if you should use an interface or not.