Summary

There are similarities between the strategy and state patterns, but the main difference is one of intents:

  • The strategy object encapsulates an algorithm
  • The state object encapsulates a behavior that depends on the internal state of an object

In both the patterns, we use polymorphism. So, for both the patterns, we define a parent interface or abstract class, and then we implement the methods defined in the parent interface or abstract class in concrete subclasses. The pattern maintains the context and depending on it decides the appropriate object to use. The biggest difference between these two patterns is that we encapsulate an algorithm into strategy classes in the strategy pattern, but we encapsulate a state into state classes in the state pattern.

The template method pattern is more like the strategy pattern; it is based on the right application of an algorithm. In this pattern, all steps are specified in the template method and some subparts are deferred to subclasses.

In the next chapter, we will learn how to use two other behavioral patterns: chain of responsibility and command.

Both are used to pass requests for actions to appropriate objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset