Saturday, January 14, 2012

State vs Strategy Design Patterns

I had to use one of these for a project I'm working on now. At first couldn't understand what the difference was between them. I mean they look identical structurally. So I started digging a little deeper into a book I use for design patterns called Professional Asp.Net Design Patterns by Scott Miller. If I can distill the answer down a bit, to me it seems like its the difference between a static and a dynamic pattern. In the case of state you give your context class the specific instance of a State object upfront (you can do this in the constructor if you like). In the case of Strategy you decide at runtime which Strategy object your context will be using. When you break it down in this way I think it makes the difference very clear. Of course there's lots of ways to do the dynamic runtime decision for which Strategy type you will use, but I chose to use the example from the book--which is to have a factory spit out the appropriate instance depending on a Strategy type enum value. Its clean and works well.

No comments:

Post a Comment