# Exploring the State Pattern

When writing code for real systems we often need to build a state machine. That is, we write code that is based on a set of states and transitions. For instance, think about a stop light or even a virtual game. For better understand this. Let’s step through an example. How about a simple controller for a gumball machine? Let’s map out the states and transitions for a gumball machine.

Now to do that, we are going to assume first that the machine is full of gumballs. So, for our first state, that’s going to be the state where we are waiting on a quarter. We’ll call that no quarter. From there we could insert a quarter and transition to the has quarter state. From there I could eject a quarter if I wanted to and I’d go back to the no quarter state. But I could also turn the crank, and I’d go to the sold state. And from the sold state I dispense the gumball, and if machine saw its gumball in it I’d go back to the no quarter state. But if the machine is sold out, then I’d go back to the sold-out state. And I’ll stay there until the machine is refilled, and then I’d go back to the no quarter state. So, we’ve modelled this simple machine as a set of states and transitions.

How do we implement something like this? The common way is to implement the state machine as a set of state constants. So here I have a constant for each state sold out, no quarter, quarter and sold, and we also have a variable typically that holds the current state. In this case, we’re going to start out with no quarter.

Then what we need to do is for each transition write a method, for instance insert quarter. What that method does is it checks to see what state we’re in, and does the appropriate thing. If we are in the quarter state and I’ve inserted a quarter, we can’t do that because there’s already a quarter there. If the machine is sold out, we’re going to have an error because we have nothing to sell. And if we are in the sold state, we’re already in the process of getting a gumball in the crank so that is an error as well. And finally, if we are in the no quarter state, then we change the state to Has Quarter.

Let’s look at another one, turn crank. Here again if we are in the sold or sold out or no quarter state, then this is an error. Otherwise if the state is quarter, then we set the state to sold and call dispense to give the gumball. Notice that we end up writing a lot of code here to handle states that either don’t make sense or that cause a lot of problems. And they are bringing their problems with our program.

You’ll also notice that each transition end up writing a method, and within that methods for every state we have a conditional test. Now let’s think about this. We know what happens in every software project – change. Let’s say we get a feature request. For instance, we might want to give a promotion so every customer has 1 in 10 chance of winning a gumball. To accomplish this one thing, we can do is add another state called winner, and then from sold state we’ll transition to winner, and if there’s a winner we’ll dispense the extra gumball.

To accomplish that we’ll first have another state as a constant. But then what we’ll need to do for the new state, we’ll have to open every existing method and add a new conditional for that state, and then we need to add to new transitions as well. Each time we need to add a new state, we must go and change the existing code. In other words, we are violating the open/closed principle.

Let’s think about a different way of doing this. Let’s take all our states and turn them into objects. And we’ll have those objects implement a common state interface.

Now, let’s look at this interface. Notice that it has a method for each state transition, so if we add a new state, all we must do is create a new state object, then we just add new methods. We don’t have to touch existing code other than inserting some methods. And now that we have a state setup, we’re going to treat one of those states as the current state. In fact, we’ll use a state field to reference one of those fields, and further, we’ll change the current state over time as time changes.

Here’s how it works. Say we are in the no quarter state, then the state field will reference the no quarter object. When the quarter is inserted, then we’ll transition to the has quarter object, and the state field will reference that. And when the crank is turned, then we’ll switch to the sold state.

Now we are modelling each state as a class with a set of methods that know what to do for each transition. Adding a new state means implementing a new class that implements the state interface. Adding new transitions means implementing new methods across the classes, but without touching the existing code.

Now that we have a high level understanding of the state design, let’s look at the details of the pattern and we’ll see how to implement this in code.

We can use the state pattern to create a better design for the gumball machine. What we are going to do is implement a state class for each possible state of the gumball machine. Instead of using integers to represent states, we’ll be using state objects.

We’ll define a state interface that contains a method for every action in the gumball machine. Each new state class will implement this interface. So, each new state will be responsible for the behavior of the machine when it is in that state. For instance, when the machine is in the no quarter state, the methods insert quarter, eject quarter, turn crank, and dispense, will all be implemented to handle this state and handle the transition to a new state. So, if you insert a quarter, the insert quarter method will transition the state from the no quarter state to the has quarter state.

We’ll be able to get rid of all the conditional code in the gumball machine. And instead delegate to the current state and let the state handle the behavior.

Let’s look at the class diagram. The gumball machine is our context, it’s the class that manages all the various states. When a request is made on the context, the context delegates that request to a state. Every state implements a common interface, the state interface. So, no matter what kind of request is made on the context, the context can delegate that request to any of the states. That means, the context doesn’t need to know how the states are implemented, so we have a loose coupling between the context and the state – which is a good thing.

The definition of the state pattern says that the pattern allows an object to alter its behavior when its internal state changes, the object will appear to change its class.

Let’s break that down a bit. First, we have each state represented by a spate class. And each of those states implements its own behavior. That is, what it should do to any request made on that state. Because every state implements the same interface, the context can delegate all requests to whatever the current state is. The state and not the context is responsible for handling the requests. And for changing the state if necessary. For instance, in the gumball machine if we get a request to insert a quarter, the context just calls the insert quarter method on the current state. If the current state is the no quarter state, then the insert quarter method will handle the transition to the has quarter state. The states have different behaviors, so in effect the context changes behavior when it changes state. And that’s what the second part of the pattern definition means when it says the object will appear to change its class. Because the state transitions from one to another and because each state has a different behavior, to the context it appears that the current state is always changing behavior as if it were changing its class. But of course, each state implements a state interface, so it is all states.

By using the state pattern, we are adhering to several OO principles. We are encapsulating what varies by making each state responsible for its own behavior and separating that logic from the context, the gumball machine class. We are favoring composition over inheritance. Rather than creating subclasses of the gumball machine to handle different states and then overriding default behavior, we are instead composing the gumball machine with a set of different states. And putting the behavior of each state into its own class. There’s very little duplication of code in this application, because each state handles each request slightly differently. And the benefit of using composition is that the context can delegate all the requests to the current state without having to worry about which state that is. Finally, we are keeping all the classes in our design closed for modification but opened for extension. With this design, we can easily add new state with minimal amount of change required for any of the existing classes. It’s true that we would have to make some small changes to the context and few of the states to add a new state, but changes are few compared to the number of changes that would be needed in our original design.

We have quite a few classes, because we have a separate class for each of the states in the gumball machine as well as an interface for them to implement. Each of the states is very similar. Let’s look at the code for the gumball machine class. Each state in the machine is represented with a separate state object, which is initialized in the gumball machine constructor. We pass the gumball machine instance to the states, so they can use the getter and setter methods to access the current sate in the state variable.

We begin in the sold out state and if a non zero number of gumballs is passed to the gumball machine constructor, we set the count of gumballs and set the initial state to the no quarter state.The methods insert quarter, eject quarter and turn crank are simple. Each method simply delegates responsibility for handling requests to the current state. We’ve also added some getters and setters to the gumball machine. So that the states can access the current state as well as the other state objects.

Now let’s take a look at the individual states beginning with the state interface. The state interface is simple. It has just four methods that each of the states need to implement.

The no quarter state is where we’ll usually begin assuming that we initialized the gumball machine with some gumballs. This class implements the state interface and the constructor takes the instance of the gumball machine and stores it in the gumball machine field. The only valid action in the no quarter state is to insert a quarter. When you do that you see a message saying that you inserted a quarter and the state transitions to he has quarter state. The rest of the methods in the no quarter state prints error messages. If you do insert a quarter in the no quarter state, the gumball machine transitions to the has quarter state.

The has quarter state class also implements the state interface as all the state classes do. And takes a gumball machine as argument in the constructor. In this state you can do one of two things. You can eject a quarter or you can turn the crank. If you eject the quarter you see a message Quarter Returned and the current state is set back to No Quarter State. If you turned the crank, then you see a message turned and the current state is set to the sold state.  And in the sold state what you want is to get a gumball.

To see how we’ll get a gumball, let’s take a look back at the gumball machine for a moment. When we turned the crank in the previous has quarter state, the turn crank method in the gumball machine was called, and this method does two things, it delegates to the current state’s turn crank method, but then it also calls the dispense method on the current state. The turn crank method changes the state from has quarter state to the sold state. So the dispense method is called on the sold state from the turn crank method in the gumball machine.

In the sold state method we release the gumball by first calling the release ball method in the gumball method. And then we check to see if there are any gumballs left, if there are, we set the state to the no quarter state. If there are no gumballs left we set the state to the sold out state. Any other action in the sold state just results in a message. In the sold out state there is no valid action, so we don’t do any state transitions in the methods of the state. The only way to get back to the no quarter state is to refill the machine which we do in the gumball machine.

The refill method in the gumball machine does this and sets the current state back to the no quarter state, so we can get gumballs again.

We can test the code by running the class  gumball machine test drive.

In this class we create a new gumball machine with 5 gumballs. The first thing we do is print the state in the gumball machine and we can see that it has 5 gumballs and is waiting for a quarter. So we insert a quarter and turn the crank, and you can see that a gumball comes rolling out of the slot. Next we print the state of the machine again, and now we can see that it has got 4 gumballs and is waiting for a quarter. We can keep getting gumballs as long as there’s gumballs left in the machine.

By structuring the implementation of the gumball machine to use the state pattern we’ve localized the behavior of each state into its own class and have eliminated the conditional statements to manage the state. This makes the code easier to maintain and more flexible.

Works Cited

Introduction to Programming: Design Patterns. Lynda.com.

# Exploring the Observer Pattern

The three main components of the Observer design pattern are: Subject, Observer and ConcreteObserver.

The observer pattern is one of the commonly used patterns. You’ll find it not only used in your own code, but you’ll find it used in various libraries and code bases. And unlike the strategy pattern which can be bit abstract to get your head around, the observer pattern is easily explained in the form of a real-world strategy.

Think about your standard newspaper magazine subscription. A publisher creates a newspaper and starts publishing it, you subscribe to the newspaper and as long you stay subscribed you’ll get issues. You can unsubscribe at any time and you’ll stop getting issues. Other people can subscribe too and they’ll all receive issues if they are published and if they stay subscribers. And if publisher ever goes out of business, obviously, you’ll stop receiving issues.

To make this example a little more formal, let’s think about a publisher and subscribers as sets of objects. We’ll start with the publisher object which any other object can send a request to subscribe, when their request is received by the publisher, the requesting object immediately becomes a subscriber. It is important that any object can be a subscriber, which means we don’t care what kind of object makes the request. Not to mention there will be objects that are not subscribers as well. We should also take note that the subscriber typically holds data of interest. That could be a stock quote, a weather temperature or any kind of data that could be interesting. And when the data changes, the subscribers are notified.

Here’s the definition of the Observer pattern:

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updates automatically.

Let’s begin with the subject defining an interface. This interface includes two methods that allow dependents to register or remove themselves from observing the subject, and includes a notify observers method that we’ll talk about in a moment.

The Observer interface just has one method called update, that’s what subjects call to let the dependents know data in the subject has changed. Now depending on your design when update is called, the dependents maybe sent a new value as part of the update call or the dependents might have to ask the subject explicitly for the new value.

The concrete subject implements notify Observers method which is called anytime data changes and this method calls the update method on each observer. It is also common to implement getters and setters in the subject to get and set the change.

The concrete observer can be any class that wants to implements the observer interface. All the concrete observer needs to do is implement the observer interface which contains the update method and that must call the subject as necessary.

Implementing the Observer Pattern

To illustrate the Observer pattern, we’ll implement a simple weather station. The weather station consists of a weather data class that can read weather information like humidity, the temperature and pressure. And the display classes that display this weather data in various configurations, like the current conditions, forecast, and statistics of the temperature like max and min temperature of the day. Each time the weather data gets new weather data it needs to update each of the displays. So, the weather data class is the subject, and the displays are the observers. They are dependent on the weather data object to let them know when there’s new data to display.

Here’s the class diagram for the weather station. We’ve got the subject interface the register observer, remove observer, and notify observer methods. And the weather data class will implement the interface, implementing each of those methods along with other concrete methods to get the weather data. We’ve also got an observer interface with one method update. Each of the displays implement this interface. And we’ve added another interface display element, which all the display classes implement as well. Each of the display class has a reference to the weather data subject, so they can register themselves as observes. And the subject weather data keeps a list of all the observers it has, so it can notify the observers when it gets new weather information.

Now, let’s look at the code for each.

Let’s begin by look at the three interfaces. We have the subject interface which has three methods. Register observer, which observers will call to register themselves with the subject. Remove observers, which observers will call to remove themselves as observers. And notify observers, which the subject will call to notify observers when there’s a change.

The observer has just only one method, update. This is the method that the subject will call when it needs to notify an observer of a change.

And the display element interface just for our convenience. This is the interface that all the display classes will implement, and they all need to implement the display method. So we can call this to get the weather information from the main class.

Now let’s check out the weather data class.

Weather data is our subject, so it implements the subject interface. The subject must keep track of all its observers. So, the weather data class has an array list observers that holds all the observers. We create this array list in the constructor of the weather data class. The register observer method simply adds an observer to this array list. And the remove observer method removes the observer from the list. Notice that both these methods take observer as an argument. And you’ll see shortly when we look at the observer code that when an observer calls these methods it passes itself in as the argument.

Now let’s look a the notify observers method.

This is how the weather data subject notifies all its observers when the change occurs. The method iterates through all the observers in the observer’s array lists and calls the observers update method, passing in the current values for its state, temperature, humidity, and pressure. If we look back at the top of the class, you’ll see those fields defined. How does this variable get set? We can set these measurements using the set measurements method.

Notice that the sets measurements method calls measurements changed, which then simply calls notify observers. Finally, we have getter methods for three properties, just in case the properties are needed for any other classes.

Now let’s look at the observers.

The current conditions display class implements the observer and display element interface. So, it needs to implement the update and display methods. First, let’s look at the constructor. When we create a display object and pass in the subject weather data, that’s so an observer can call the subjects methods like register observer to be added to the list of observers. In the constructor, we save the reference to the weather data object and then use it to register this object as an observer. The current conditions display is notified the change from the weather data object when its update method is called. The update method receives the new weather data information and saves the data that’s needed by the display. The current condition saves the temperature and the humidity, but doesn’t bother saving the pressure because it is not needed for this display. And whenever the display element gets new data form the subject, it needs to update its display showing the new data so we call display which simply prints the new current conditions to the console.

So, we have our subject and we have our observers, so let’s look at the main class.

Here we can see how we put everything together. The first thing we do in the weather station is to create our subject, a weather data object. Then we crate three observers for our weather station, a current condition display, a statistic display, and a forecast display. And we pass the weather data object to each observer. Remember that each observer saves the weather data object and then immediately calls the register object method to register itself as an observer. Then we change the data in the weather data subject simulating the weather station reporting new data from sensors. When we do this the weather data object notifies each of the observers of the change which causes each observer to update its display. We should see each observer create an updated display each time we change the data by calling set measurements.

Because we used the observer pattern, we can easily add new displays at any time without changing the weather data class at all. The weather data class doesn’t know any specifics of the observers; it just knows how to keep track of them and update them when weather changes.

Works Cited

Burris, Eddie. “Chapter 8 Factory Method.” Programming in the Large with Design Patterns. Leawood, Kan: Pretty Print, 2012. 110-122. Print.

Freeman, Eric, and Elisabeth Freeman. “Chapter 4. The Factory Method Pattern: Baking with OO Goodness.” Head First Design Patterns. Sebastopol, CA: O’Reilly Media, 2005. N. pag. Print.

Foundations of Programming: Design Patterns. Lynda.com.

# Exploring the Factory Method Pattern

The standard way of creating an object is to instantiate a concrete class directly with the new operator:

SomeClass sc = new SomeClass();

One of the drawbacks of using the new operator to create an object is the need to specify the type of object to create. Specifically, it creates a dependency between your code and the class or type of object created. Sometimes a more general solution is needed, one that allows control over when an instance of an object is created but leaves open or delegates to another class the specific type of object to create.

Decoupling object creation from object use results in code that is more flexible and extendable.

Also, the advice “program to an interface, not an implementation” also applies to object creation. You could create an object with the new operator.

class ClientCodeC{

public clientCodeC(){

SupportingClass sc = new SupportingClass();

}

}

However, the reference to concrete class SupportingClass at line 3 is an example of programming to an implementation. If there is nothing about clientCodeC that requires an instance of SupportingClass, it is usually better to program to an abstract interface that will result in the creation of an instance of SupportingClass or another type that is compatible with the client code.

But how do we do that? That is precisely the problem solved by the Factory Method design pattern.

The Factory design pattern has four main components. The class Creator declares a factory method createProduct(). createProduct() returns an object of type Product. Subclasses of Creator override the factory method to create and return a concrete instance of Product.

There are many forms. Here’s one.

Here’s another.

Notice how it differs from the structure diagram in the previous example. In the previous example there is a one-to-many relationship between concrete creators and concrete products. With iteration in Java there is a one-to-one relationship between  concrete collection classes and concrete iterators. Both are valid forms of the pattern.

But what happens when we have multiple store franchises. Let’s say that we have two stores, one wants to make NY style pizzas and the other wants to make Chicago style pizzas.

Now we’re in a situation where we are going to need either a much more complex factory or two different factories to make the two different styles of pizza or we’ll have to put all the logic for creating the different pizzas back into the store. All this options make for a more complicated code, and many more places where we’ll have to change code if we add new pizza types or change a topping.

The current implementation, below, also violates the open/closed principle. There is no way to extend the current solution to work with other credit card processing services without modifying the code.

The store needs to use the same order pizza method so that the prepare, bake, cut, box the pizzas in the same way, but have the flexibility of creating different styles of pizza objects, one creating NY style pizzas while the other creates Chicago style pizzas. What we want is to have two different kinds of pizza stores that use the same time testing algorithm to make pizzas but that can make two different kinds of pizzas. But without being dependent on the concrete types of pizzas on any way.

To create our store franchises, we’ll change the design to use the Factory Method Pattern.

The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Let’s see what that means by looking at the new design for the pizza store.

First we’re going to change the pizza store class so that it is an abstract class. All the pizza stores in the franchise will extend this class. To make sure that all the pizza stores use the same method for preparing pizzas for customers, in other words the same algorithm, the pizza store abstract class will implement the order pizza method. This is the shared code all the stores use for preparing the pizza, no matter what store we’re in and what type of pizza it is.

However, the two pizza stores that extend this class, NY store and Chicago store, will implement their own create pizza methods. That way each store gets to decide what kind of pizzas it will make. The NY store will make NY style pizzas while the Chicago store will make Chicago style pizzas. This is what is meant in the factory method pattern definition, when we say the factory method pattern lets a class defer instantiation to subclasses. Here the abstract class pizza store is deferring instantiation of concrete pizzas to the individual pizza store that extend it.

The pizza class is basically going to be the same, but now we’re going to have many different types of pizzas. A set of pizzas for the NY style pizza store and a set of pizzas for the Chicago style pizza store. The NY pizza store will be responsible for creating the NY style pizza and the Chicago style pizza store will be responsible for creating the Chicago style pizzas.

To create a pizza, we’ll first instantiate the kind of store that we want. Imaging choosing between walking into a NY style pizza store or a Chicago style pizza store. Once we’re in the store, we can order a pizza. Remember this method is implemented by the abstract class pizza store. So, no matter which pizza store we’re in when we make an order, we’re guaranteed to get the same brilliant pizza making algorithm to produce quality pizzas.

The first step in the order pizza algorithm is to create a pizza. The create pizza method is implemented by the individual stores. So, if we’re in a NY style pizza store we’ll get the method implemented by that store. We pass the type of pizza to the create pizza method. This method creates the right type of pizza based on the type and once it is returned to the order pizza method in the store, the order pizza method can prepare the pizza to the customer.

Here’s our main class.

Recall that in the Simple Factory idiom, we first created a factory and then passed the factory to the store. We no longer need the factory because the pizza stores are created the pizzas directly. Remember that the pizza stores order pizza method, implemented in the pizza store abstract class creates the kind of pizzas that we want depending on which store we call the method on.

PizzaStore is implemented as a Factory Method because we want to be able to create a product that varies by region. With the Factory Method, each region gets its own concrete factory that knows how to make pizzas which are appropriate for the area.

Works Cited

Burris, Eddie. “Chapter 8 Factory Method.” Programming in the Large with Design Patterns. Leawood, Kan: Pretty Print, 2012. 110-122. Print.

Freeman, Eric, and Elisabeth Freeman. “Chapter 4. The Factory Method Pattern: Baking with OO Goodness.” Head First Design Patterns. Sebastopol, CA: O’Reilly Media, 2005. N. pag. Print

# Understanding the Simple Factory Idiom

The goal of the simple factory idiom is to separate the process of creating concrete objects to reduce the dependency of the client from the concrete implementations.

To implement the simple factory we need three things:

1. A factory, the pizza factory.
2. The products the factory makes which are the pizza objects.
3. The client that uses the factory, which is the pizza store.

So, let’s take our pizza creation code, encapsulate it, separate it. And we’ll encapsulate it in a class called Factory.

Why a Factory? Because this is a class whose sole responsibility is creating pizzas — it’s a pizza factory.

To do that we’re going to take this conditional code for creating pizzas and put it into a separate class, in a method name createPizza. Each time we want a pizza, we’ll call the method, pass it a type, and the method will make a pizza for us and return an object that implements the pizza interface.

Now all this creation will be in a separate class, nicely separated form the restaurant code. So, let’s integrate this with our client code or restaurant code. Let’s assume that we’ve created a factory object already. And call it to create the pizza, passing it the type variable.

Our order pizza method no longer has to worry about the concrete type of the pizza. It could be a veggie pizza, a cheese pizza, or a pizza we haven’t even heard of yet. We know whatever type gets returned by the factory, it implements the pizza interface. And that’s all we care about.

So we call this object design the simple factory idiom. The simple factory idiom allows us to decouple the process of creating objects from the client that uses those objects. Our pizza store used a simple factory to create pizzas, so that the pizza store doesn’t have to worry about the details of the various pizza types. The factory deals with that. While the pizza store focuses on getting the pizza ready for the customer.

We start we the client of the restaurant, the pizza store. And then we have our factory. The factory is the only place the concrete types of pizzas are known.  And then we have the products, what the factory makes or pizzas, and there could be many concrete types of those.

To generalize this a bit, we could look at the same diagram without pizzas.

And here we have the client, a factory, and a set of products that implement a common interface.

Now, one thing to note. This is not a full fledged official pattern. It is more of an idiom that’s commonly used. That said it is the first step to understanding some of the more common design patterns.

And now we’ll put everything together in a main class called the pizza test drive  which will create a pizza store and use it to create pizzas.

Works Cited

Freeman, Eric, and Elisabeth Freeman. “Chapter 4. The Factory Method Pattern: Baking with OO Goodness.” Head First Design Patterns. Sebastopol, CA: O’Reilly Media, 2005. N. pag. Print

# Read this and you’ll Know more about Design Patterns than you ever did!

Context: Engineers look for routine solutions before resorting to original problem solving. Design is probably the most challenging activity in the software development life cycle. There is no algorithm for deriving abstract solution models from requirements. The best the discipline of software engineering can offer are methods, techniques, heuristics, and design patterns.

Solution: A design pattern is problem-solution pair. Design patterns are discovered rather than invented. Design patterns are paragons of good design. A design pattern, and more generally a design, is an abstraction of an implementation. What is being reused is the structure or organization of the code. The solution provided is the design and not the code. A design pattern is not a concrete design or implementation, such as an algorithm that can be used as-is, but rather a generic solution that must be adapted to the specific needs of the problem at hand. The purpose of the design process is to determine how the eventual code will be structured or organized into modules. The output of the design process is an abstract solution model typically expressed with a symbolic modeling language such as UML.

Pros:

• Studying design patterns helps to develop the intellectual concepts and principles needed to solve unique design problems from first principles. Design patterns define a shared vocabulary for discussing design and architecture. Catalogs of design patterns define a shared vocabulary at the right level of abstraction for efficient communication of design ideas.
• Knowing popular design patterns make it easier to learn class libraries that use design patterns. For example, the classes and interfaces that make up the Java IO package are confusing to many new Java programmers simply because they aren’t familiar with the decorator design pattern.
• Knowledge of design patterns simplifies software design by reducing the number of design problems that must be solved from first principles. Design problems that match documented design patterns have ready-made solutions. The remaining problems that don’t match documented design patterns must be solved from first principles.

Cons (not really! lol):

• Applying design patterns is easier than solving design problems from first principles but their application still requires thoughtful decision making. You must be familiar enough with existing patterns to recognize the problem is one for which a design pattern exists.

Here’s the important things to remember:

• First, design (and more generally engineering) is about balancing conflicting forces or constraints.
• Second, design patterns provide general solutions at a medium level of abstraction. They don’t give exact answers, and at the same time, they are more concrete and practical than abstract principles or strategies.
• Finally, patterns aren’t dogma.

Here’s where Kids get Confused:

Intent Matters!!!!!

Design patterns are NOT distinguished by their static structure alone.

Can you tell me which represents state pattern and which represents strategy pattern?

It is of course impossible. What makes a design pattern unique is its intent? The intent of a pattern is the problem solved or reason for using it. The intent of State pattern is to allow an object to alter its behavior when its internal state changes. The intent of the Strategy pattern is to encapsulate different algorithms or behaviors and make them interchangeable from the client’s perspective. The structure is the same for both solutions.

Works Cited:

Burris, Eddie. “Introduction to Design Patterns.” Programming in the Large with Design Patterns. Leawood, Kan: Pretty Print, 2012. 11-33. Print.