The Template Method

Intent: We want to abstract out a common theme from different cases that have different implementations of an algorithm.

Example: Often systems/frameworks have a fixed workflow where the steps are always executed in a specific sequence, but the actions taken in each step vary by application context. Template method separates the common workflow from the individual steps it executes/organizes. The template method may also contain common conditionals or other logic that does not vary by implementation.

images

Figure 20: Template method example diagram.

A Conceptual Diagram

Qualities and Principles: The template method separates a common workflow from its varying implementations. The workflow is not redundantly implemented, and each implementation is about one version of the process. All implementations are interchangeable. The interface of the template method is derived from the needs of clients. The template method encapsulates the workflow itself, the varying implementations (their number and nature), and which are currently active, making them open-closed.

Testing: The template method (Workflow, in the example) can be tested using a mock implementation (see p. 38) that can capture and record how it is used to ensure its methods are called correctly. Each implementation (WorkflowA, etc., in the example) can have its own test; if protected methods are used, the test can be made a subclass in each case.

Questions and Concerns: The template method is intended to abstract out the steps of an algorithm. If the steps are actually different algorithms, then the template method may have weak cohesion. When this is the case, the step methods to correct this should delegate to behavioral objects rather than embedding the code in the actual implementation class. If this is done, then the “single algorithm” would be the workflow itself.

Many patterns have template method as part of their implementation: decorator (see p. 28) and chain of responsibility (see p. 24) are typical examples.

For more information: https://tinyurl.com/y5c3faea

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

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