Introduction to the Strategy design pattern

No.of Views981
Bookmarked0 times
Downloads 
Votes0
By  Chinna Srihari   On  23 Oct 2010 03:10:25
Tag : Design Patterns , General
The Strategy pattern involves separating an algorithm from its host class and putting it in a separate class. When there are multiple strategies available for an algorithm, for a given problem it is always better to separate them in to different objects. If the algorithms are all kept in the one class, the class will be become a big messy conditional statements.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 
Definition
The Strategy pattern involves separating an algorithm from its host class and putting it in a separate class. When there are multiple strategies available for an algorithm, for a given problem it is always better to separate them in to different objects. If the algorithms are all kept in the one class, the class will be become a big messy conditional statements.
 
The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it.
 
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
 
Note:
 
1.       Strategy is like Template Method except that strategy consist details whereas template provides skeleton for the algorithm.
2.       State is like Strategy except in its objective.
3.       Strategy lets us change the internal object. Decorator lets us change the covering, underlying object remains same.
 
Design
 
Let us say that us are implementing text hashing for the system. During requirements decision is to implement the MD5 hashing, during development added with SHA1 for another requirement, and it kept continued. Finally decision is to implement with couple of options and based on the client strategy it can be changed.
 
 
UML Diagram
 
Please refer to the attached doc for the images 
 
 
Code            
    public abstract class HashingStrategy
    {
        public abstract void HashingInterface(string text);
    }
 
    public class MD5Hashing : HashingStrategy
    {
        public override void HashingInterface(string text)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
 
            Byte[] bytes;
            bytes = ASCIIEncoding.Default.GetBytes(text);
 
            Byte[] encodedBytes;
            encodedBytes = md5.ComputeHash(bytes);
 
            string A = BitConverter.ToString(encodedBytes);
        }
    }
 
    public class HashingContext
    {
        private HashingStrategy _hashingStrategy;
 
        public HashingContext(HashingStrategy hashingStrategy)
        {
            _hashingStrategy = hashingStrategy;
        }
 
        public void HashPassword(string text)
        {
            _hashingStrategy.HashingInterface(text);
        }
    }
 
    public class SHA1Hashing : HashingStrategy
    {
        public override void HashingInterface(string text)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
 
            Byte[] bytes;
            bytes = ASCIIEncoding.Default.GetBytes(text);
 
            Byte[] encodedBytes;
            encodedBytes = sha1.ComputeHash(bytes);
 
            string A = BitConverter.ToString(encodedBytes);
        }
    }
 
    public class SHA256Hashing : HashingStrategy
    {
        public override void HashingInterface(string text)
        {
            SHA256 sha256 = new SHA256CryptoServiceProvider();
 
            Byte[] bytes;
            bytes = ASCIIEncoding.Default.GetBytes(text);
 
            Byte[] encodedBytes;
            encodedBytes = sha256.ComputeHash(bytes);
 
            string A = BitConverter.ToString(encodedBytes);
        }
    }
 
    public class SHA384Hashing : HashingStrategy
    {
        public override void HashingInterface(string text)
        {
            SHA384 sha384 = new SHA384CryptoServiceProvider();
 
            Byte[] bytes;
            bytes = ASCIIEncoding.Default.GetBytes(text);
 
 
            Byte[] encodedBytes;
            encodedBytes = sha384.ComputeHash(bytes);
 
            string A = BitConverter.ToString(encodedBytes);
        }
    }
 
Client
 
    HashingContext context;
           
            context = new HashingContext(new SHA1Hashing());
            context.HashPassword("Chinna Sushma");
 
            context = new HashingContext(new SHA384Hashing());
            h.HashPassword("Chinna Lohetha");
 
Hope this helps
Chinna

Download Sample

Download source files -53 kb

 
Sign Up to vote for this article
 
About Author
 
Chinna Srihari
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-17 Jun 2010
Home Page-
Blog Page-
Having 12 + years of IT experience, 2.5 years as Technical Management experience and 1.5 year of onsite coordinator experience and rest 8+ years of technical activities including Project Leader, Tech Lead, Designer, PQL, and Developer experience in Quality Management System (CMM-level 5, SEI-CMM-level 5).
 
 
Other popularSectionarticles
    This is a quite simple design pattern, let me tell you one thing there are many design patterns that they are implicitly singletons. I rather recommend to understanding this one first before going through other patterns.
    Published Date : 21/Oct/2010
    As a developer we might have noticed that creation of some class is very difficult and number of time that we need to create. Such object creation every time is very expensive in terms of system resources. If we can cache that kind of object show how will surely boost the application performance and resource usage can be saved. This where object pool design pattern will help development community to cache the objects. Some time it is also called as Object cache or Resource cache design pattern.
    Published Date : 21/Oct/2010
    The Command pattern creates distance between the client that requests an operation and the object that can perform it.
    Published Date : 20/Sep/2010
    Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
    Published Date : 22/Oct/2010
    A fully initialized instance to be copied or cloned. The Prototype pattern specifies the kind of objects to create using a prototypical instance.
    Published Date : 22/Oct/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top