Monday, May 04, 2020

The startegy pattern




The Strategy pattern defines a family of algorithms whose individual behaviours are encapsulated allowing them to be interchangeable. Strategy lets the algorithm vary independently from clients that use it. You can use this pattern to implement the Open/Close principle. 



Problem 


I'm building a digital wallet, users can choose the kind of encryption they need to protect their data with. Since the process of encrypting is the same. That is choosing their data, performing the encryption and storing it, we do not wish to duplicate the process for each new encryption type. Also, we want the flexibility to create new encryptions in the future and not affect the existing encrypted data. The Strategy Pattern can do just this.   

Analysis 


We need to be able to encapsulate the encryption algorithms and switch between them at runtime. Without the client being aware of the algorithms themselves. 

Solution 


First, we define an encryption interface IEncryption. We can now create different algorithms as the implementation of this interface. We now have three encryption classes class SHA1, class SHA256 and class SHA512 that implement the IEncryption interface. Then we create an Encryption Service class called EncryptionService that maintains the reference to the algorithms and decouples the client form the actual encryption classes. Alternatively, we could have substituted the interface with an Abstract class, this would allow us to define a default encryption to use.


Illustration 







Code


  public class Program
    {
        private static void Main(string[] args)
        {
            List encsvc = new List { new EncryptionService(new SHA1()), new EncryptionService(new SHA256()), new EncryptionService(new SHA512()) };

            foreach (var con in encsvc)
            {
                con.DoEncryption();
            }

            Console.ReadKey();
        }
    }


    public interface IEncryption

    {
        public void Encrypt();
    }


    public class SHA1 : IEncryption

    {
        public void Encrypt()
        {
            Console.WriteLine(
              "Encrypt using SHA1");
        }
    }

    internal class SHA256 : IEncryption

    {
        public void Encrypt()
        {
            Console.WriteLine(
              "Encrypt using SHA256");
        }
    }

    internal class SHA512 : IEncryption

    {
        public void Encrypt()
        {
            Console.WriteLine(
              "Encrypt using SHA512");
        }
    }

    internal class EncryptionService

    {
        private IEncryption encryption;


        public EncryptionService(IEncryption encryption)
        {
            this.encryption = encryption;
        }

        public void DoEncryption()
        {
            encryption.Encrypt();
        }
    }
}

No comments: