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

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
TypeScript Design Patterns
Published in: Aug 2016Publisher: PacktISBN-13: 9781785280832

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