Reader small image

You're reading from  TypeScript Design Patterns

Product typeBook
Published inAug 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785280832
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Vilic Vane
Vilic Vane
author image
Vilic Vane

Vilic Vane is a JavaScript engineer with over 8 years of experience in web development. He started following the TypeScript project since it went public, and hes also a contributor of the project. He is now working at Ruff, a startup company building an IoT platform that runs JavaScript on embedded devices.
Read more about Vilic Vane

Right arrow

Chapter 6. Behavioral Design Patterns: Continuous

In the previous chapter, we've already talked about some of the behavioral design patterns. We'll be continuing with more patterns in this category in this chapter, including: Strategy Pattern, State Pattern, Template Method Pattern, Observer Pattern, and Visitor Pattern.

Many of these patterns share the same idea: unify the shape and vary the details. Here is a quick overview:

  • Strategy Pattern and Template Pattern: Defines the same outline of algorithms

  • State Pattern: Provides different behavior for objects in different states with the same interface

  • Observer Pattern: Provides a unified process of handling subject changes and notifying observers

  • Visitor Pattern: Does similar jobs as Strategy Pattern sometimes, but avoids an over complex interface that might be required for Strategy Pattern to handle objects in many different types

Patterns that will be discussed in this chapter could be applied in different scopes just as many patterns in...

Strategy Pattern


It's common that a program has similar outlines for processing different targets with different detailed algorithms. Strategy Pattern encapsulates those algorithms and makes them interchangeable within the shared outline.

Consider conflicting merging processes of data synchronization, which we talked about in Chapter 2, The Challenge of Increasing Complexity. Before refactoring, the code was like this:

if (type === 'value') { 
  // ... 
} else if (type === 'increment') { 
  // ... 
} else if (type === 'set') { 
  // ... 
} 

But later we found out that we could actually extract the same outlines from different phases of the synchronization process, and encapsulate them as different strategies. After refactoring, the outline of the code became as follows:

let strategy = strategies[type]; 
strategy.operation(); 

We get a lot of ways to compose and organize those strategy objects or classes sometimes in JavaScript. A possible structure...

State Pattern


It's possible for some objects to behave completely differently when they are in different states. Let's think about an easy example first. Consider rendering and interacting with a custom button in two states: enabled and disabled. When the button is enabled, it lights up and changes its style to active on a mouse hover, and of course, it handles clicks; when disabled, it dims and no longer cares about mouse events.

We may think of an abstraction with two operations: render (with a parameter that indicates whether the mouse is hovering) and click; along with two states: enabled and disabled. We can even divide deeper and have state active, but that won't be necessary in our case.

And now we can have StateEnabled with both render and click methods implemented, while having StateDisabled with only render method implemented because it does not care about the hover parameter. In this example, we are expecting every method of the states being callable. So we can have the abstract...

Template Method Pattern


When we are talking about subclassing or inheriting, the building is usually built from the bottom up. Subclasses inherit the basis and then provide more. However, it could be useful to reverse the structure sometimes as well.

Consider Strategy Pattern which defines the outline of a process and has interchangeable algorithms as strategies. If we apply this structure under the hierarchy of classes, we will have Template Method Pattern.

A template method is an abstract method (optionally with default implementation) and acts as a placeholder under the outline of a larger process. Subclasses override or implement related methods to modify or complete the behaviors. Imaging the skeleton of a TextReader, we are expecting its subclasses to handle text files from different storage media, detect different encodings and read all the text. We may consider a structure like this:

The TextReader in this example has a method readAllText that reads all text from a resource by two...

Observer Pattern


Observer Pattern is an important Pattern backed by an important idea in software engineering. And it is usually a key part of MVC architecture and its variants as well.

If you have ever written an application with a rich user interface without a framework like Angular or a solution with React, you might probably have struggled with changing class names and other properties of UI elements. More specifically, the code that controls those properties of the same group of elements lies every branch related to the elements in related event listeners, just to keep the elements being correctly updated.

Consider a "Do" button of which the disabled property should be determined by the status of a WebSocket connection to a server and whether the currently active item is done. Every time the status of either the connection or the active item gets updated, we'll need to update the button correspondingly. The most "handy" way could be two somewhat identical groups of code being put in two...

Visitor Pattern


Visitor Pattern provides a uniformed interface for visiting different data or objects while allowing detailed operations in concrete visitors to vary. Visitor Pattern is usually used with composites, and it is widely used for walking through data structures like abstract syntax tree (AST). But to make it easier for those who are not familiar with compiler stuff, we will provide a simpler example.

Consider a DOM-like tree containing multiple elements to render:

[ 
  Text { 
    content: "Hello, " 
  }, 
  BoldText { 
    content: "TypeScript" 
  }, 
  Text { 
    content: "! Popular editors:\n" 
  }, 
  UnorderedList { 
    items: [ 
      ListItem { 
        content: "Visual Studio Code" 
      }, 
      ListItem { 
        content: "Visual Studio" 
      }, 
      ListItem { 
        content: "WebStorm" 
      } 
    ] 
  } 
] 

The rendering result in HTML...

Summary


In this chapter, we've talked about other behavior design patterns as complements to the former chapter, including Strategy, State, Template Method, Observer and Visitor Pattern.

Strategy Pattern is so common and useful that it may appear in a project several times, with different forms. And you might not know you were using Observer Pattern with implementation in a daily framework.

After walking through those patterns, you might find there are many ideas in common behind each pattern. It is worth thinking what's behind them and even letting the outline go in your mind.

In the next chapter, we'll continue with some handy patterns related to JavaScript and TypeScript, and important scenarios of those languages.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
TypeScript Design Patterns
Published in: Aug 2016Publisher: PacktISBN-13: 9781785280832
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Vilic Vane

Vilic Vane is a JavaScript engineer with over 8 years of experience in web development. He started following the TypeScript project since it went public, and hes also a contributor of the project. He is now working at Ruff, a startup company building an IoT platform that runs JavaScript on embedded devices.
Read more about Vilic Vane