samedi 25 juillet 2020

Which design-patterns is Koa framework built upon?

I was reading Addy Osmani's book Learning Javascript Design Patterns, which I think is a great book on design patterns. When I came upon the Flyweight design pattern, I found it pretty familiar. It seemed like I've seen this pattern getting used in any project.

The project I was thinking about was node-oidc provider, an oidc-provider package written in node.js using Koa framework.

In the package, an instance constant is created which embodies properties and methods to it and is shared all across the application. The instance is created using WeakMap collection in file weak_cache.js and is first imported into the file provider.js.

Now, why I think this is very much similar to flyweight design pattern is because of the statements in the pattern's description.

It aims to minimize the use of memory in an application by sharing as much data as possible with related objects (e.g application configuration, state and so on).

In practice, Flyweight data sharing can involve taking several similar objects or data constructs used by a number of objects and placing this data into a single external object.

Albeit, I understand it isn't exactly flyweight pattern(and I might be wrong on this), but the instance constant pretty much resembles the external object in the above statements.

Upon further speculations, I started to think about what other patterns are involved in a simple Koa application. Though the application built on top of Koa will use its own design patterns, but for simplicity & brevity let's consider a simple Koa application as our model for this question.

The key statements in Koa documentation which I think may help us in understanding the design patterns employed are:

A Koa application is an object containing an array of middleware functions which are composed and executed in a stack-like manner upon request.

const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);

From the use of new operator, one can think of Constructor pattern. All the imported packages tell us the usage of the Module pattern.

I know the question is too broad and might be subjective in nature, but I'm trying to see the practical use-cases/scenarios of the patterns I studied in the book.

Aucun commentaire:

Enregistrer un commentaire