DEV Community

Discussion on: Design Patterns - Strategy Pattern in JavaScript

Collapse
 
onexdata profile image
Nick Steele • Edited

This looks like it only covers older object-oriented style strategy implementations. This doesn't really do the strategy pattern justice in 2020.

Here is a set of functions on an object, and each object has a process functor that does something different. This object is the core of an analytics engine and replaces many hundreds of lines of code and is very extensible:

const events = {
'heartBeat': { id: 0, process: (e) => ({}) },
'mediatimeupdate': { id: 1, ignore: true, process: (e) => e },
'mediaplay': { id: 8, process: (e) => ({ t: e.detail.plyr.currentTime }) },
'mediaplaying': { id: 9, process: (e) => ({ t: e.detail.plyr.currentTime }) },
'touch': { id: 13, update: 'lookingAt', process: (e) => ({ x: e.x, y: e.y }) },
'focus': { id: 14, update: 'lookingAt', process: (e) => ({ x: e.x, y: e.y }) },
'cartAdd': { id: 19, process: (e) => ({ p: e.id }) },
'cartUpdateQty': { id: 20, process: (e) => ({ p: e.thing.id, q: e.qty }) },
'cartClear': { id: 21, process: (e) => ({}) },
}

Now that you have an object of strategies, you create a 1-line dispatcher for the aspect of event processing...

// Here is the actual "strategy" pattern in this design, the way of calling things based on what is being asked for, the "switchboard" that handles routing to different code based on needs...
const $event = (name, payload, stream = defaultStream) => stream(event[name].process(payload))

Now you can pass in any browser or custom event, and it will process it and pull out only the parts you're looking for, and pass that into any stream you're looking for...

this.$event('cartAdd', thing)

...all this was done with the absolute minimum amount of code possible, and it's incredibly powerful, pushing all the code into a single object of functions, and the dispatches become join points on a cross-cutting concern of "events", and events can contain any payload; their processors are all defined in the same place. Every time you see an $event call in your code, you know you are simply dispatching the event itself. Nothing left to do.

This type of use of the strategy pattern elevates your code from OOP to AOP and cuts your LOC drastically and makes things much easier to understand with zero repetition.