Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Design & Architecture » The difference between the two GOF patterns "Strategy" and "State"

The difference between the two GOF patterns "Strategy" and "State"

The GOF Strategy and State patterns are remarkably similiar and it is really only a minor implementation detail that distinguishes the two.

Author Rank :
Page Views : 13992
Downloads : 141
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
StatePatternSample.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The GOF Strategy and State patterns are remarkably similiar and it is really only a minor implementation detail that distinguishes the two.

 

Part 1. Strategy Pattern

 

The way I like to think of the strategy pattern is (1) encapsulation of a method into a class and (2) being able to swap out this method with different implementations. 

 

We'll often come across a situation when building code where we have long "if-then-else" chains in our class methods which determine how the method will behave. This is a perfect situation to refactor to a Strategy pattern, especially if we have cut-n-pasted the "if-then-else" chain to other methods. These chains can be replaced by a single strategy.

 

So, basically all we are doing is creating a class with "pluggable" functionality. For instance, if we have the following interface that defines a "Calculate" strategy:

 

interface ICalculator

{

    int Calculate(int inputA, int inputB);

}

 

And two implementations of the strategy:

 

class Adder : ICalculator

{ 

    #region ICalculator Members

 

    public int Calculate(int inputA, int inputB)

    {

        return inputA + inputB;

    }

 

    #endregion

}

 

class Subtractor : ICalculator

{ 

    #region ICalculator Members

 

    public int Calculate(int inputA, int inputB)

    {

        return inputA - inputB;

    }

 

    #endregion

}

 

We can create a class where we can "plug-in" either strategy to be used for execution of the "Calculate()" method below:

 

class NumberChanger

{

    public NumberChanger(ICalculator calculationStrategy)

    {

        m_calculationStrategy = calculationStrategy;

        m_state = 1;

    }

 

    private ICalculator m_calculationStrategy;

    private int m_state;

 

    public int State

    {

        get { return m_state; }

    }

 

    internal ICalculator CalculationStrategy

    {

        get { return m_calculationStrategy; }

        set { m_calculationStrategy = value; }

    }

 

    public int Calculate(int input)

    {

        m_state = m_calculationStrategy.Calculate(m_state, input);

        return m_state;

    }

}

 

This is how we would use the class:

 

StrategyPattern.NumberChanger strategyCalculator = new StrategyPattern.NumberChanger(new Adder());

while (strategyCalculator.State < 10)

{

    Console.WriteLine("StrategyPattern.NumberChanger.State = " + strategyCalculator.State);

    strategyCalculator.Calculate(1);    

}

 

strategyCalculator.CalculationStrategy = new Subtractor();

while (strategyCalculator.State > 0)

{

    Console.WriteLine("StrategyPattern.NumberChanger.State = " + strategyCalculator.State);

    strategyCalculator.Calculate(1);

}

 

And our result is:

 

StrategyPattern.NumberChanger.State = 1

StrategyPattern.NumberChanger.State = 2

StrategyPattern.NumberChanger.State = 3

StrategyPattern.NumberChanger.State = 4

StrategyPattern.NumberChanger.State = 5

StrategyPattern.NumberChanger.State = 6

StrategyPattern.NumberChanger.State = 7

StrategyPattern.NumberChanger.State = 8

StrategyPattern.NumberChanger.State = 9

StrategyPattern.NumberChanger.State = 10

StrategyPattern.NumberChanger.State = 9

StrategyPattern.NumberChanger.State = 8

StrategyPattern.NumberChanger.State = 7

StrategyPattern.NumberChanger.State = 6

StrategyPattern.NumberChanger.State = 5

StrategyPattern.NumberChanger.State = 4

StrategyPattern.NumberChanger.State = 3

StrategyPattern.NumberChanger.State = 2

StrategyPattern.NumberChanger.State = 1

 

Part 2. The State Pattern

 

The way I like to think of the State Pattern is simply a Strategy Pattern where the class manages it's own strategy based on it's state (thus the name).

 

If we have the same ICalculator, Adder, and Subtractor classes from above, we could use them in an implementation of the State pattern as follows (Note how the class sets its own strategy based on its state in the Calculate() method):

 

class NumberChanger

{

    public NumberChanger()

    {

        m_calculationStrategy = m_adder;

        m_state = 1;

    }

 

    private ICalculator m_calculationStrategy;

    private int m_state; 

    private static ICalculator m_adder = new Adder();

    private static ICalculator m_subtractor = new Subtractor();

 

    public int State

    {

        get { return m_state; }

    }

 

    internal ICalculator CalculationStrategy

    {

        get { return m_calculationStrategy; }

        set { m_calculationStrategy = value; }

    }

 

    public int Calculate(int input)

    {

        m_state = m_calculationStrategy.Calculate(m_state, input);

        // this is where the interal state is evaluated and

        // the strategy is set

        if (m_state >= 10)

        {

            m_calculationStrategy = m_subtractor;

        }

        else if (m_state < 1)

        {

            m_calculationStrategy = m_adder;

        } 

        return m_state;

    }

}

 

And our implementation looks like this:

 

StatePattern.NumberChanger stateCalculator = new StatePattern.NumberChanger();

while (stateCalculator.State > 0)

{

    Console.WriteLine("StatePattern.NumberChanger.State = " + stateCalculator.State);

    stateCalculator.Calculate(1);

}

 

For a similiar final result:

 

StatePattern.NumberChanger.State = 1

StatePattern.NumberChanger.State = 2

StatePattern.NumberChanger.State = 3

StatePattern.NumberChanger.State = 4

StatePattern.NumberChanger.State = 5

StatePattern.NumberChanger.State = 6

StatePattern.NumberChanger.State = 7

StatePattern.NumberChanger.State = 8

StatePattern.NumberChanger.State = 9

StatePattern.NumberChanger.State = 10

StatePattern.NumberChanger.State = 9

StatePattern.NumberChanger.State = 8

StatePattern.NumberChanger.State = 7

StatePattern.NumberChanger.State = 6

StatePattern.NumberChanger.State = 5

StatePattern.NumberChanger.State = 4

StatePattern.NumberChanger.State = 3

StatePattern.NumberChanger.State = 2

StatePattern.NumberChanger.State = 1

 

Conclusion.

 

I hope this article gives you a better idea of the state and strategy patterns and how closely they are related. Both these patterns are really a Strategy pattern at the core where the only difference is that the State pattern maintains its own strategy.

 

Until next time,

Happy Coding. 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Great article! by elranu On March 12, 2007
thanks for this article, simple article, to understand this two patterns. Thanks, Ranu www.ranu.com.ar
Reply | Email | Modify 
State Pattern by jeff On May 31, 2007
Thanks for the article. I personally cant think of anywhere to use the state pattern though. It seems to me, to be non scalable.
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.