Pattern Comparison

Pattern Comparison

There are considerable similarities between the Strategy and State patterns, but the main difference is one of intent:

  • A Strategy object encapsulates an algorithm

  • A State object encapsulates a state-dependent behavior (and possibly state transitions)

Both patterns are concerned with polymorphism. Both patterns define a parent interface or abstract class and a series of subclasses that implement the methods therein. And both patterns have a context that they maintain and use to decide on state transitions. So, the biggest difference between the patterns is that we encapsulate an algorithm into strategy classes in the Strategy pattern, but we encapsulate state into state classes in the State pattern.

The Template Method pattern is more like the Strategy pattern in that it is algorithm based. The steps of the algorithm are specified in the Template Method and some are deferred to domain classes.

These similarities and differences are illustrated in the simple theory code in Example 7-1, Example 7-3, and Example 7-5. Table 7-1 summarizes them.

Table 7-1. Comparison of Strategy, State, and Template Method patterns

 

Strategy

State

Template Method

Action achieved by

Context invokes Strategy

Client invokes Context

Algorithm invoking Operations

Switching modes based on

Client inspecting Context

State inspecting Context

Instantiation of classes in Client

Context/IPrimitives contains

Current Strategy

Current State

Operational interface

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.