Quando si sviluppano applicazioni JavaScript, si potrebbe aver bisogno di creare oggetti in un certo modo predefinito o di riutilizzare una classe modificandola o adattandola a diversi casi d’uso.

Naturalmente non è conveniente risolvere questi problemi più volte.

È qui che i design pattern di JavaScript vengono in aiuto.

I design pattern JavaScript vi forniscono un modo strutturato e ripetibile per affrontare i problemi più comuni nello sviluppo di JavaScript.

In questa guida vedremo cosa sono i design pattern JavaScript e come usarli nelle vostre applicazioni JavaScript.

Cos’È un Design Pattern JavaScript?

I design pattern JavaScript sono soluzioni template ripetibili per i problemi più frequenti nello sviluppo di applicazioni JavaScript.

L’idea è semplice: programmatrici e programmatori di tutto il mondo, fin dagli albori dello sviluppo, hanno affrontato una serie di problemi ricorrenti durante lo sviluppo di applicazioni. Nel corso del tempo, alcuni sviluppatori hanno scelto di documentare i modi collaudati per affrontare questi problemi, in modo che altri potessero fare riferimento alle soluzioni con facilità.

Man mano che un numero sempre maggiore di professionisti sceglieva di usare queste soluzioni e ne riconosceva l’efficacia, queste sono state accettate come modalità standard di risoluzione dei problemi e hanno preso il nome di “design pattern”.

Man mano che l’importanza dei design pattern è stata compresa, questi sono stati ulteriormente sviluppati e standardizzati. Oggi la maggior parte dei design pattern moderni ha una struttura definita, è organizzata in più categorie e viene insegnata nei corsi di laurea in informatica come argomento indipendente.

Tipi di Design Pattern JavaScript

Ecco alcune delle classificazioni più popolari dei design pattern JavaScript.

Creativi

I design pattern creativi sono quelli che aiutano a risolvere i problemi legati alla creazione e alla gestione di nuove istanze di oggetti in JavaScript. Può trattarsi di questioni semplici come limitare una classe a un solo oggetto o complesse come definire un metodo intricato per selezionare e aggiungere ogni caratteristica di un oggetto JavaScript.

Alcuni esempi di design pattern creativi sono Singleton, Factory, Abstract Factory e Builder, tra gli altri.

Strutturali

I design pattern strutturali sono quelli che aiutano a risolvere i problemi di gestione della struttura (o schema) degli oggetti JavaScript. Questi problemi possono includere la creazione di una relazione tra due oggetti diversi o l’astrazione di alcune caratteristiche di un oggetto per utenti specifici.

Alcuni esempi di design pattern strutturali sono Adapter, Bridge, Composite e Facade.

Comportamentali

I design pattern comportamentali sono quelli che aiutano a risolvere i problemi relativi al passaggio del controllo (e della responsabilità) tra vari oggetti. Questi problemi possono riguardare il controllo dell’accesso a una lista collegata o la creazione di un’unica entità in grado di controllare l’accesso a più tipi di oggetti.

Alcuni esempi di design pattern comportamentali sono Command, Iterator, Memento e Observer.

Concurrency

I design pattern concurrency sono quelli che aiutano a risolvere i problemi legati al multi-threading e al multitasking. Questi problemi possono riguardare il mantenimento di un oggetto attivo tra più oggetti disponibili o la gestione di eventi multipli forniti a un sistema, applicando un demultiplexing degli input in arrivo e gestendoli pezzo per pezzo.

Alcuni esempi di design pattern concurrency sono gli oggetti attivi, il nuclear react e lo scheduler.

Architetturali

I design pattern architetturali sono quelli che aiutano a risolvere i problemi di progettazione del software in senso lato. In genere sono legati a come progettare il sistema per garantire un’elevata disponibilità, mitigare i rischi ed evitare i colli di bottiglia delle prestazioni.

Due esempi di design pattern architetturali sono MVC e MVVM.

Elementi di un Design Pattern

Quasi tutti i design pattern possono essere suddivisi in un insieme di quattro importanti componenti. Essi sono:

  • Nome del pattern: si usa per identificare un design pattern durante la comunicazione con gli altri utenti. Alcuni esempi sono “singleton”, “prototype” e altri ancora.
  • Problema: descrive l’obiettivo del design pattern. Si tratta di una piccola descrizione del problema che il design pattern sta cercando di risolvere. Può anche includere uno scenario di esempio per spiegare meglio il problema. Può anche contenere un elenco di condizioni da soddisfare affinché il pattern risolva completamente il problema.
  • Soluzione: è la soluzione al problema in questione, composta da elementi come classi, metodi, interfacce, ecc. È la parte più importante di un design pattern: comporta relazioni, responsabilità e collaboratori di vari elementi che sono chiaramente definiti.
  • Risultati: si tratta di un’analisi di quanto il pattern sia stato in grado di risolvere il problema. Vengono discussi aspetti come l’utilizzo dello spazio e del tempo e gli approcci alternativi per risolvere lo stesso problema.

Se volete saperne di più sui design pattern e sulla loro nascita, la MSU offre del materiale di studio sintetico a cui fare riferimento.

Perché Usare i Design Pattern?

I motivi per cui dovresti usare i design pattern sono molteplici:

  • Sono collaudati e testati: con un design pattern, avete una soluzione collaudata al vostro problema (a patto che il design pattern corrisponda alla descrizione del problema). Non dovete perdere tempo a cercare soluzioni alternative e potete essere certi di avere una soluzione che si occupa dell’ottimizzazione delle prestazioni di base.
  • Sono facili da capire: i design pattern sono pensati per essere piccoli, semplici e facili da capire. Non dovete avere un’esperienza decennale in un settore specifico per capire quale design pattern usare. Sono volutamente generici (non sono limitati a un particolare linguaggio di programmazione) e possono essere compresi da chiunque abbia sufficienti capacità di risoluzione dei problemi. Questo è utile anche quando c’è un cambio di guardia nel vostro team tecnico: un frammento di codice che si basa su un design pattern è più facile da capire per chiunque stia iniziando nel settore dello sviluppo software.
  • Sono semplici da implementare: la maggior parte dei design pattern sono molto semplici, come vedrete più avanti nel nostro articolo. Non è necessario conoscere molti concetti di programmazione per implementarli nel vostro codice.
  • Propongono un’architettura del codice facilmente riutilizzabile: la riusabilità e la pulizia del codice sono molto incoraggiate nell’industria tecnologica e i design pattern possono aiutarvi a raggiungere questo obiettivo. Poiché questi schemi rappresentano un modo standard di risolvere i problemi, i loro progettisti si sono preoccupati di garantire che l’architettura dell’app rimanga riutilizzabile, flessibile e compatibile con la maggior parte delle forme di scrittura del codice.
  • Risparmiano tempo e dimensioni dell’app: uno dei maggiori vantaggi di affidarsi a un insieme di soluzioni standard è che vi aiutano a risparmiare tempo durante l’implementazione. È molto probabile che tutto il vostro team di sviluppo conosca bene i design pattern, quindi sarà più facile per loro pianificare, comunicare e collaborare durante l’implementazione. Le soluzioni sperimentate e testate significano che è molto probabile che non perderete risorse o che non farete una deviazione durante la creazione di alcune funzionalità, risparmiando tempo e spazio. Inoltre, la maggior parte dei linguaggi di programmazione offre librerie di template standard che implementano già alcuni design pattern comuni come Iterator e Observer.

I 20 Migliori Design Pattern JavaScript da Padroneggiare

Ora che avete capito in cosa consiste un design pattern e perché ne avete bisogno, approfondiamo il modo in cui alcuni dei design pattern JavaScript più utilizzati possono essere implementati in un’applicazione JavaScript.

Creativi

Iniziamo la discussione con alcuni design pattern fondamentali e facili da imparare.

1. Singleton

Il pattern Singleton è uno dei design pattern più utilizzati nel settore dello sviluppo software. Il problema che si propone di risolvere è quello di mantenere una sola istanza di una classe. Questo può essere utile quando si istanziano oggetti che richiedono molte risorse, come i gestori (handler) di database.

Ecco come potete implementarlo in JavaScript:

function SingletonFoo() {

   let fooInstance = null;

   // For our reference, let's create a counter that will track the number of active instances
   let count = 0;

   function printCount() {
   	console.log("Number of instances: " + count);
   }

   function init() {
   	// For our reference, we'll increase the count by one whenever init() is called
   	count++;

   	// Do the initialization of the resource-intensive object here and return it
   	return {}
   }

   function createInstance() {
   	if (fooInstance == null) {
       	fooInstance = init();
   	}
   	return fooInstance;
   }

   function closeInstance() {
   	count--;
   	fooInstance = null;
   }

   return {
   	initialize: createInstance,
   	close: closeInstance,
   	printCount: printCount
   }
}

let foo = SingletonFoo();

foo.printCount() // Prints 0
foo.initialize()
foo.printCount() // Prints 1
foo.initialize()
foo.printCount() // Still prints 1
foo.initialize()
foo.printCount() // Still 1
foo.close()
foo.printCount() // Prints 0

Sebbene serva allo scopo, lo schema Singleton è noto per complicare il debugging, poiché maschera le dipendenze e controlla l’accesso all’inizializzazione o alla distruzione delle istanze di una classe.

2. Factory

Anche il metodo Factory è uno dei design pattern più popolari. Il problema che il metodo Factory mira a risolvere è la creazione di oggetti senza utilizzare il costruttore convenzionale. Al contrario, il metodo accetta la configurazione (o descrizione) dell’oggetto che si desidera e restituisce l’oggetto appena creato.

Ecco come potete implementarlo in JavaScript:

function Factory() {
   this.createDog = function (breed) {
   	let dog;

   	if (breed === "labrador") {
       	dog = new Labrador();
   	} else if (breed === "bulldog") {
       	dog = new Bulldog();
   	} else if (breed === "golden retriever") {
       	dog = new GoldenRetriever();
   	} else if (breed === "german shepherd") {
       	dog = new GermanShepherd();
   	}

   	dog.breed = breed;
   	dog.printInfo = function () {
       	console.log("nnBreed: " + dog.breed + "nShedding Level (out of 5): " + dog.sheddingLevel + "nCoat Length: " + dog.coatLength + "nCoat Type: " + dog.coatType)
   	}

   	return dog;
   }
}

function Labrador() {
   this.sheddingLevel = 4
   this.coatLength = "short"
   this.coatType = "double"
}

function Bulldog() {
   this.sheddingLevel = 3
   this.coatLength = "short"
   this.coatType = "smooth"
}

function GoldenRetriever() {
   this.sheddingLevel = 4
   this.coatLength = "medium"
   this.coatType = "double"
}

function GermanShepherd() {
   this.sheddingLevel = 4
   this.coatLength = "medium"
   this.coatType = "double"
}

function run() {

   let dogs = [];
   let factory = new Factory();

   dogs.push(factory.createDog("labrador"));
   dogs.push(factory.createDog("bulldog"));
   dogs.push(factory.createDog("golden retriever"));
   dogs.push(factory.createDog("german shepherd"));

   for (var i = 0, len = dogs.length; i < len; i++) {
   	dogs[i].printInfo();
   }
}

run()

/**
Output:

Breed: labrador
Shedding Level (out of 5): 4
Coat Length: short
Coat Type: double


Breed: bulldog
Shedding Level (out of 5): 3
Coat Length: short
Coat Type: smooth


Breed: golden retriever
Shedding Level (out of 5): 4
Coat Length: medium
Coat Type: double


Breed: german shepherd
Shedding Level (out of 5): 4
Coat Length: medium
Coat Type: double
*/

Il design pattern Factory controlla il modo in cui gli oggetti verranno creati e vi fornisce un modo rapido per creare nuovi oggetti, oltre a un’interfaccia uniforme che definisce le proprietà che gli oggetti avranno. Potete aggiungere tutte le razze di cani che volete, ma finché i metodi e le proprietà esposti dai tipi di razza rimangono gli stessi, funzioneranno perfettamente.

Tuttavia, tenete presente che il pattern Factory può spesso portare a un gran numero di classi che possono essere difficili da gestire.

3. Abstract Factory

Il metodo Abstract Factory porta il metodo Factory a un livello superiore, rendendo le factory astratte e quindi sostituibili senza che l’ambiente chiamante conosca l’esatta factory utilizzata o il suo funzionamento interno. L’ambiente chiamante sa solo che tutte le factory hanno un insieme di metodi comuni che può chiamare per eseguire l’azione di istanziazione.

Ecco come può essere implementato l’esempio precedente:

// A factory to create dogs
function DogFactory() {
   // Notice that the create function is now createPet instead of createDog, since we need
   // it to be uniform across the other factories that will be used with this
   this.createPet = function (breed) {
   	let dog;

   	if (breed === "labrador") {
       	dog = new Labrador();
   	} else if (breed === "pug") {
       	dog = new Pug();
   	}

   	dog.breed = breed;
   	dog.printInfo = function () {
       	console.log("nnType: " + dog.type + "nBreed: " + dog.breed + "nSize: " + dog.size)
   	}

   	return dog;
   }
}

// A factory to create cats
function CatFactory() {
   this.createPet = function (breed) {
   	let cat;

   	if (breed === "ragdoll") {
       	cat = new Ragdoll();
   	} else if (breed === "singapura") {
       	cat = new Singapura();
   	}

   	cat.breed = breed;
   	cat.printInfo = function () {
       	console.log("nnType: " + cat.type + "nBreed: " + cat.breed + "nSize: " + cat.size)
   	}

   	return cat;
   }
}

// Dog and cat breed definitions
function Labrador() {
   this.type = "dog"
   this.size = "large"
}

function Pug() {
   this.type = "dog"
   this.size = "small"
}

function Ragdoll() {
   this.type = "cat"
   this.size = "large"
}

function Singapura() {
   this.type = "cat"
   this.size = "small"
}

function run() {

   let pets = [];

   // Initialize the two factories
   let catFactory = new CatFactory();
   let dogFactory = new DogFactory();

   // Create a common petFactory that can produce both cats and dogs
   // Set it to produce dogs first
   let petFactory = dogFactory;

   pets.push(petFactory.createPet("labrador"));
   pets.push(petFactory.createPet("pug"));

   // Set the petFactory to produce cats
   petFactory = catFactory;

   pets.push(petFactory.createPet("ragdoll"));
   pets.push(petFactory.createPet("singapura"));

   for (var i = 0, len = pets.length; i < len; i++) {
   	pets[i].printInfo();
   }
}

run()

/**
Output:

Type: dog
Breed: labrador
Size: large


Type: dog
Breed: pug
Size: small


Type: cat
Breed: ragdoll
Size: large


Type: cat
Breed: singapura
Size: small

*/

Il pattern Abstract Factory consente di scambiare facilmente le factory concrete e aiuta a promuovere l’uniformità tra le factory e i prodotti creati. Tuttavia, può diventare difficile introdurre nuovi tipi di prodotti, poiché è necessario apportare modifiche a più classi per inserire nuovi metodi/proprietà.

4. Builder

Il modello Builder è uno dei design pattern JavaScript creativi più complessi ma flessibili. Vi permette di costruire una per una tutte le caratteristiche del vostro prodotto, offrendovi il pieno controllo su come viene costruito il vostro oggetto, pur astraendo dai dettagli interni.

Nell’intricato esempio che segue, vedrete il design pattern Builder in azione insieme a Director che vi aiuterà a preparare le pizze!

// Here's the PizzaBuilder (you can also call it the chef)
function PizzaBuilder() {
   let base
   let sauce
   let cheese
   let toppings = []

   // The definition of pizza is hidden from the customers
   function Pizza(base, sauce, cheese, toppings) {
   	this.base = base
   	this.sauce = sauce
   	this.cheese = cheese
   	this.toppings = toppings

   	this.printInfo = function() {
       	console.log("This pizza has " + this.base + " base with " + this.sauce + " sauce "
       	+ (this.cheese !== undefined ? "with cheese. " : "without cheese. ")
       	+ (this.toppings.length !== 0 ? "It has the following toppings: " + toppings.toString() : ""))
   	}
   }

   // You can request the PizzaBuilder (/chef) to perform any of the following actions on your pizza
   return {
   	addFlatbreadBase: function() {
       	base = "flatbread"
       	return this;
   	},
   	addTomatoSauce: function() {
       	sauce = "tomato"
       	return this;
   	},
   	addAlfredoSauce: function() {
       	sauce = "alfredo"
       	return this;
   	},
   	addCheese: function() {
       	cheese = "parmesan"
       	return this;
   	},
   	addOlives: function() {
       	toppings.push("olives")
       	return this
   	},
   	addJalapeno: function() {
       	toppings.push("jalapeno")
       	return this
   	},
   	cook: function() {
       	if (base === null){
           	console.log("Can't make a pizza without a base")
           	return
       	}
       	return new Pizza(base, sauce, cheese, toppings)
   	}
   }

}

// This is the Director for the PizzaBuilder, aka the PizzaShop.
// It contains a list of preset steps that can be used to prepare common pizzas (aka recipes!)
function PizzaShop() {
   return {
   	makePizzaMargherita: function() {
       	pizzaBuilder = new PizzaBuilder()
       	pizzaMargherita = pizzaBuilder.addFlatbreadBase().addTomatoSauce().addCheese().addOlives().cook()
       	return pizzaMargherita
   	},
   	makePizzaAlfredo: function() {
       	pizzaBuilder = new PizzaBuilder()
       	pizzaAlfredo = pizzaBuilder.addFlatbreadBase().addAlfredoSauce().addCheese().addJalapeno().cook()
       	return pizzaAlfredo
   	},
   	makePizzaMarinara: function() {
       	pizzaBuilder = new PizzaBuilder()
       	pizzaMarinara = pizzaBuilder.addFlatbreadBase().addTomatoSauce().addOlives().cook()
       	return pizzaMarinara
   	}
   }
}

// Here's where the customer can request pizzas from
function run() {

   let pizzaShop = new PizzaShop()

   // You can ask for one of the popular pizza recipes...
   let pizzaMargherita = pizzaShop.makePizzaMargherita()
   pizzaMargherita.printInfo()
   // Output: This pizza has flatbread base with tomato sauce with cheese. It has the following toppings: olives

   let pizzaAlfredo = pizzaShop.makePizzaAlfredo()
   pizzaAlfredo.printInfo()
   // Output: This pizza has flatbread base with alfredo sauce with cheese. It has the following toppings: jalapeno

   let pizzaMarinara = pizzaShop.makePizzaMarinara()
   pizzaMarinara.printInfo()
   // Output: This pizza has flatbread base with tomato sauce without cheese. It has the following toppings: olives

   // Or send your custom request directly to the chef!
   let chef = PizzaBuilder()
   let customPizza = chef.addFlatbreadBase().addTomatoSauce().addCheese().addOlives().addJalapeno().cook()
   customPizza.printInfo()
   // Output: This pizza has flatbread base with tomato sauce with cheese. It has the following toppings: olives,jalapeno

}

run()

Potete abbinare il Builder a un Director, come mostra la classe PizzaShop nell’esempio precedente, per predefinire una serie di passaggi da seguire ogni volta per costruire una variante standard del vostro prodotto, per esempio una ricetta specifica per le vostre pizze.

L’unico problema di questo design pattern è che è piuttosto complesso da configurare e mantenere. Tuttavia, aggiungere nuove funzionalità in questo modo è più semplice rispetto al metodo Factory.

5. Prototype

Il design pattern Prototype è un modo semplice e veloce per creare nuovi oggetti a partire da oggetti esistenti, clonandoli.

Viene prima creato un oggetto prototipo che può essere clonato più volte per creare nuovi oggetti. È utile quando l’istanziazione diretta di un oggetto è un’operazione che richiede più risorse rispetto alla creazione di una copia di un oggetto esistente.

Nell’esempio che segue, vedrete come usare il pattern Prototype per creare nuovi documenti basati su un template di documento prestabilito:

// Defining how a document would look like
function Document() {
   this.header = "Acme Co"
   this.footer = "For internal use only"
   this.pages = 2
   this.text = ""
 
   this.addText = function(text) {
   	this.text += text
   }

   // Method to help you see the contents of the object
   this.printInfo = function() {
   	console.log("nnHeader: " + this.header + "nFooter: " + this.footer + "nPages: " + this.pages + "nText: " + this.text)
   }

 
}

// A protype (or template) for creating new blank documents with boilerplate information
function DocumentPrototype(baseDocument) {
   this.baseDocument = baseDocument
 
   // This is where the magic happens. A new document object is created and is assigned the values of the current object
   this.clone = function() {
   	let document = new Document();

   	document.header = this.baseDocument.header
   	document.footer = this.baseDocument.footer
   	document.pages = this.baseDocument.pages
   	document.text = this.baseDocument.text

   	return document
   }
}

function run() {
   // Create a document to use as the base for the prototype
   let baseDocument = new Document()

   // Make some changes to the prototype
   baseDocument.addText("This text was added before cloning and will be common in both documents. ")

   let prototype = new DocumentPrototype(baseDocument)

   // Create two documents from the prototype
   let doc1 = prototype.clone()
   let doc2 = prototype.clone()

   // Make some changes to both objects
   doc1.pages = 3

   doc1.addText("This is document 1")
   doc2.addText("This is document 2")

   // Print their values
   doc1.printInfo()
   /* Output:
   	Header: Acme Co
   	Footer: For internal use only
   	Pages: 3
   	Text: This text was added before cloning and will be common in both documents. This is document 1
	*/

   doc2.printInfo()
   /** Output:
   	Header: Acme Co
   	Footer: For internal use only
   	Pages: 2
   	Text: This text was added before cloning and will be common in both documents. This is document 2
	*/
}

run()

Il metodo Prototype è ottimo nei casi in cui gran parte degli oggetti condividono gli stessi valori o quando la creazione di un nuovo oggetto è piuttosto costosa. Tuttavia, sembra eccessivo nei casi in cui non avete bisogno di più di qualche istanza della classe.

Strutturali

I design pattern strutturali vi aiutano a organizzare la vostra logica di business fornendovi metodi collaudati di strutturare le classi. Esistono diversi design pattern strutturali che si adattano a casi d’uso specifici.

6. Adapter

Un problema comune nella creazione di applicazioni è quello di consentire la collaborazione tra classi incompatibili.

Un buon esempio per capire questo aspetto è il mantenimento della compatibilità all’indietro. Se scrivete una nuova versione di una classe, è naturale volere che sia facilmente utilizzabile in tutti i punti in cui funzionava la vecchia versione. Tuttavia, se apportate delle modifiche di rottura, come la rimozione o l’aggiornamento di metodi che erano fondamentali per il funzionamento della vecchia versione, potreste ritrovarvi con una classe che necessita dell’aggiornamento di tutti i suoi client per poter essere eseguita.

In questi casi, il design pattern Adapter può essere d’aiuto.

Il design pattern Adapter fornisce un’astrazione che colma il divario tra i metodi e le proprietà della nuova classe e i metodi e le proprietà della vecchia classe. Ha la stessa interfaccia della vecchia classe, ma contiene la logica per mappare i vecchi metodi con quelli nuovi per eseguire operazioni simili. È simile al modo in cui una presa di corrente funge da adattatore tra una spina di tipo americano e una di tipo europeo.

Ecco un esempio:

// Old bot
function Robot() {

   this.walk = function(numberOfSteps) {
   	// code to make the robot walk
   	console.log("walked " + numberOfSteps + " steps")
   }

   this.sit = function() {
   	// code to make the robot sit
   	console.log("sit")
   }

}

// New bot that does not have the walk function anymore
// but instead has functions to control each step independently
function AdvancedRobot(botName) {
   // the new bot has a name as well
   this.name = botName

   this.sit = function() {
   	// code to make the robot sit
   	console.log("sit")
   }

   this.rightStepForward = function() {
   	// code to take 1 step from right leg forward
   	console.log("right step forward")
   }

   this.leftStepForward = function () {
   	// code to take 1 step from left leg forward
   	console.log("left step forward")
   }
}

function RobotAdapter(botName) {
   // No references to the old interfact since that is usually
   // phased out of development
   const robot = new AdvancedRobot(botName)

   // The adapter defines the walk function by using the
   // two step controls. You now have room to choose which leg to begin/end with,
   // and do something at each step.
   this.walk = function(numberOfSteps) {
   	for (let i=0; i<numberOfSteps; i++) {
     	 
       	if (i % 2 === 0) {
           	robot.rightStepForward()
       	} else {
           	robot.leftStepForward()
       	}
   	}
   }

   this.sit = robot.sit

}

function run() {

   let robot = new Robot()

   robot.sit()
   // Output: sit
   robot.walk(5)
   // Output: walked 5 steps

   robot = new RobotAdapter("my bot")

   robot.sit()
   // Output: sit
   robot.walk(5)
   // Output:
   // right step forward
   // left step forward
   // right step forward
   // left step forward
   // right step forward

}

run()

Il problema principale di questo design pattern è che aggiunge complessità al vostro codice sorgente. Dovevate già gestire due classi diverse e ora avete un’altra classe, l’adapter, da gestire.

7. Bridge

Espandendo il pattern Adapter, il pattern Bridge fornisce sia alla classe che al client interfacce separate in modo che entrambi possano funzionare anche in caso di interfacce native incompatibili.

Aiuta a sviluppare un’interfaccia molto libera tra i due tipi di oggetti. Questo aiuta anche a migliorare l’estensibilità delle interfacce e delle loro implementazioni per ottenere la massima flessibilità.

Ecco come potete usarlo:

// The TV and speaker share the same interface
function TV() {
   this.increaseVolume = function() {
   	// logic to increase TV volume
   }

   this.decreaseVolume = function() {
   	// logic to decrease TV volume
   }

   this.mute = function() {
   	// logic to mute TV audio
   }
}

function Speaker() {
   this.increaseVolume = function() {
   	// logic to increase speaker volume
   }

   this.decreaseVolume = function() {
   	// logic to decrease speaker volume
   }

   this.mute() = function() {
   	// logic to mute speaker audio
   }
}

// The two remotes make use of the same common interface
// that supports volume up and volume down features
function SimpleRemote(device) {
   this.pressVolumeDownKey = function() {
   	device.decreaseVolume()
   }

   this.pressVolumeUpKey = function() {
   	device.increaseVolume()
   }
}

function AdvancedRemote(device) {

   this.pressVolumeDownKey = function() {
   	device.decreaseVolume()
   }

   this.pressVolumeUpKey = function() {
   	device.increaseVolume()
   }

   this.pressMuteKey = function() {
   	device.mute()
   }
}

function run() {

   let tv = new TV()
   let speaker = new Speaker()

   let tvSimpleRemote = new SimpleRemote(tv)
   let tvAdvancedRemote = new AdvancedRemote(tv)

   let speakerSimpleRemote = new SimpleRemote(speaker)
   let speakerAdvancedRemote = new AdvancedRemote(speaker)

   // The methods listed in pair below will have the same effect
   // on their target devices
   tvSimpleRemote.pressVolumeDownKey()
   tvAdvancedRemote.pressVolumeDownKey()

   tvSimpleRemote.pressVolumeUpKey()
   tvAdvancedRemote.pressVolumeUpKey()

   // The advanced remote has additional functionality
   tvAdvancedRemote.pressMuteKey()

   speakerSimpleRemote.pressVolumeDownKey()
   speakerAdvancedRemote.pressVolumeDownKey()

   speakerSimpleRemote.pressVolumeUpKey()
   speakerAdvancedRemote.pressVolumeUpKey()

   speakerAdvancedRemote.pressMuteKey()
}

Come avrete già intuito, il pattern Bridge aumenta notevolmente la complessità della codebase. Inoltre, la maggior parte delle interfacce finisce per avere una sola implementazione nei casi d’uso reali, per cui la riusabilità del codice non è molto vantaggiosa.

8. Composite

Il design pattern Composite vi aiuta a strutturare e gestire facilmente oggetti ed entità simili. L’idea di base del pattern Composite è che gli oggetti e i loro contenitori logici possono essere rappresentati utilizzando un’unica classe astratta (che può memorizzare dati/metodi relativi all’oggetto e riferimenti a se stessa per il contenitore).

L’utilizzo del pattern Composite è più sensato quando il vostro modello di dati assomiglia a una struttura ad albero. Tuttavia, non dovreste cercare di trasformare un modello di dati non ad albero in un modello di dati ad albero solo per il gusto di usare il pattern Composite, perché così facendo spesso si perde molta flessibilità.

Nell’esempio che segue, vedrete come utilizzare il design pattern Composite per costruire un sistema di imballaggio per i prodotti di un ecommerce che può anche calcolare il valore totale dell’ordine per ogni confezione:

// A product class, that acts as a Leaf node
function Product(name, price) {
   this.name = name
   this.price = price

   this.getTotalPrice = function() {
   	return this.price
   }
}

// A box class, that acts as a parent/child node
function Box(name) {
   this.contents = []
   this.name = name

   // Helper function to add an item to the box
   this.add = function(content){
   	this.contents.push(content)
   }

   // Helper function to remove an item from the box
   this.remove = function() {
   	var length = this.contents.length;
   	for (var i = 0; i < length; i++) {
       	if (this.contents[i] === child) {
           	this.contents.splice(i, 1);
           	return;
       	}
   	}
   }

   // Helper function to get one item from the box
   this.getContent = function(position) {
   	return this.contents[position]
   }

   // Helper function to get the total count of the items in the box
   this.getTotalCount = function() {
   	return this.contents.length
   }

   // Helper function to calculate the total price of all items in the box
   this.getTotalPrice = function() {
   	let totalPrice = 0;

   	for (let i=0; i < this.getTotalCount(); i++){
       	totalPrice += this.getContent(i).getTotalPrice()
   	}

   	return totalPrice
   }
}

function run() {

   // Let's create some electronics
   const mobilePhone = new Product("mobile phone," 1000)
   const phoneCase = new Product("phone case," 30)
   const screenProtector = new Product("screen protector," 20)

   // and some stationery products
   const pen = new Product("pen," 2)
   const pencil = new Product("pencil," 0.5)
   const eraser = new Product("eraser," 0.5)
   const stickyNotes = new Product("sticky notes," 10)

   // and put them in separate boxes
   const electronicsBox = new Box("electronics")
   electronicsBox.add(mobilePhone)
   electronicsBox.add(phoneCase)
   electronicsBox.add(screenProtector)
 
   const stationeryBox = new Box("stationery")
   stationeryBox.add(pen)
   stationeryBox.add(pencil)
   stationeryBox.add(eraser)
   stationeryBox.add(stickyNotes)

   // and finally, put them into one big box for convenient shipping
   const package = new Box('package')
   package.add(electronicsBox)
   package.add(stationeryBox)

   // Here's an easy way to calculate the total order value
   console.log("Total order price: USD " + package.getTotalPrice())
   // Output: USD 1063
}

run()

L’aspetto più negativo dell’utilizzo del pattern Composite è che le modifiche alle interfacce dei componenti possono farsi molto impegnative in futuro. La progettazione delle interfacce richiede tempo e fatica e la natura ad albero del modello di dati può rendere molto difficile apportare modifiche a piacimento.

9. Decorator

Il pattern Decorator vi aiuta ad aggiungere nuove funzionalità agli oggetti esistenti semplicemente avvolgendole all’interno di un nuovo oggetto. È simile al modo in cui potete avvolgere un pacco regalo già confezionato con nuova carta da regalo tutte le volte che volete: ogni impacchettamento vi permette di aggiungere tutte le funzionalità che desiderate, quindi è un’ottima soluzione in termini di flessibilità.

Da un punto di vista tecnico, non è prevista l’ereditarietà, quindi c’è una maggiore libertà nella progettazione della logica aziendale.

Nell’esempio che segue, vedrete come il pattern Decorator vi aiuta ad aggiungere altre funzionalità a una classe standard Customer:

function Customer(name, age) {
   this.name = name
   this.age = age

   this.printInfo = function() {
   	console.log("Customer:nName : " + this.name + " | Age: " + this.age)
   }
}

function DecoratedCustomer(customer, location) {
   this.customer = customer
   this.name = customer.name
   this.age = customer.age
   this.location = location

   this.printInfo = function() {
   	console.log("Decorated Customer:nName: " + this.name + " | Age: " + this.age + " | Location: " + this.location)
   }
}

function run() {
   let customer = new Customer("John," 25)
   customer.printInfo()
   // Output:
   // Customer:
   // Name : John | Age: 25

   let decoratedCustomer = new DecoratedCustomer(customer, "FL")
   decoratedCustomer.printInfo()
   // Output:
   // Customer:
   // Name : John | Age: 25 | Location: FL
}

run()

Gli svantaggi di questo pattern includono un’elevata complessità del codice, poiché non esiste uno schema standard definito per aggiungere nuove funzionalità utilizzando i decorator. Alla fine del ciclo di vita del software potreste ritrovarvi con molti decorator non uniformi e/o simili.

Se non fate attenzione durante la progettazione dei decorator, potreste finire per progettare alcuni decorator in modo che siano logicamente dipendenti da altri. Se non si risolve questo problema, la rimozione o la ristrutturazione dei decorator in un secondo momento può compromettere la stabilità dell’applicazione.

10. Facade

Quando si costruisce la maggior parte delle applicazioni del mondo reale, la logica di business risulta di solito piuttosto complessa. Potreste ritrovarvi con più oggetti e metodi coinvolti nell’esecuzione delle operazioni principali della vostra applicazione. Tenere traccia delle loro inizializzazioni, delle dipendenze, dell’ordine corretto di esecuzione dei metodi e così via, può essere piuttosto complicato e soggetto a errori se non viene fatto correttamente.

Il design pattern Facade vi aiuta a creare un’astrazione tra l’ambiente che invoca le operazioni di cui sopra e gli oggetti e i metodi coinvolti nel completamento di tali operazioni. Questa astrazione ospita la logica per inizializzare gli oggetti, tracciare le loro dipendenze e altre attività importanti. L’ambiente chiamante non ha informazioni su come viene eseguita un’operazione. Potete aggiornare liberamente la logica senza apportare modifiche al client chiamante.

Ecco come potete utilizzarlo in un’applicazione:

/**
* Let's say you're trying to build an online store. It will have multiple components and
* complex business logic. In the example below, you will find a tiny segment of an online
* store composed together using the Facade design pattern. The various manager and helper
* classes are defined first of all.
*/


function CartManager() {
   this.getItems = function() {
   	// logic to return items
   	return []
   }
 
   this.clearCart = function() {
   	// logic to clear cart
   }
}

function InvoiceManager() {
   this.createInvoice = function(items) {
   	// logic to create invoice
   	return {}
   }

   this.notifyCustomerOfFailure = function(invoice) {
   	// logic to notify customer
   }

   this.updateInvoicePaymentDetails = function(paymentResult) {
   	// logic to update invoice after payment attempt
   }
}

function PaymentProcessor() {
   this.processPayment = function(invoice) {
   	// logic to initiate and process payment
   	return {}
   }
}

function WarehouseManager() {
   this.prepareForShipping = function(items, invoice) {
   	// logic to prepare the items to be shipped
   }
}

// This is where facade comes in. You create an additional interface on top of your
// existing interfaces to define the business logic clearly. This interface exposes
// very simple, high-level methods for the calling environment.
function OnlineStore() {
   this.name = "Online Store"
 
   this.placeOrder = function() {
   	let cartManager = new CartManager()
   	let items = cartManager.getItems()

   	let invoiceManager = new InvoiceManager()
   	let invoice = invoiceManager.createInvoice(items)
 	 
   	let paymentResult = new PaymentProcessor().processPayment(invoice)
   	invoiceManager.updateInvoicePaymentDetails(paymentResult)

   	if (paymentResult.status === 'success') {
       	new WarehouseManager().prepareForShipping(items, invoice)
       	cartManager.clearCart()
   	} else {
       	invoiceManager.notifyCustomerOfFailure(invoice)
   	}
 	 
   }
}

// The calling environment is unaware of what goes on when somebody clicks a button to
// place the order. You can easily change the underlying business logic without breaking
// your calling environment.
function run() {
   let onlineStore = new OnlineStore()

   onlineStore.placeOrder()
}

Un aspetto negativo dell’utilizzo del pattern Facade è che aggiunge un ulteriore livello di astrazione tra la logica aziendale e il client, richiedendo così una manutenzione aggiuntiva. Spesso questo aumenta la complessità complessiva della base di codice.

Inoltre, la classe Facade diventa una dipendenza obbligatoria per il funzionamento della vostra applicazione: ciò significa che qualsiasi errore nella classe Facade ha un impatto diretto sul funzionamento della vostra applicazione.

11. Flyweight

Il pattern Flyweight vi aiuta a risolvere i problemi che coinvolgono oggetti con componenti ripetuti in modo efficiente dal punto di vista della memoria, aiutandovi a riutilizzare i componenti comuni del vostro pool di oggetti. Questo aiuta a ridurre il carico sulla memoria e a velocizzare i tempi di esecuzione.

Nell’esempio che segue, una frase di grandi dimensioni viene memorizzata utilizzando il design pattern Flyweight. Invece di memorizzare ogni carattere nel momento in cui si presenta, il programma identifica l’insieme dei caratteri distinti che sono stati utilizzati per scrivere il paragrafo e i loro tipi (numero o alfabeto) e costruisce dei flyweight riutilizzabili per ogni carattere che contengono i dettagli del carattere e del tipo memorizzati.

In seguito, l’array principale si limita a memorizzare un elenco di riferimenti a questi pesi volanti nell’ordine in cui si presentano nella frase, invece di memorizzare un’istanza dell’oggetto carattere ogni volta che si presenta.

In questo modo la memoria occupata dalla frase si riduce della metà. Tenete presente che questa è una spiegazione molto elementare di come i processori di testo memorizzano il testo.

// A simple Character class that stores the value, type, and position of a character
function Character(value, type, position) {
   this.value = value
   this.type = type
   this.position = position
}

// A Flyweight class that stores character value and type combinations
function CharacterFlyweight(value, type) {
   this.value = value
   this.type = type
}

// A factory to automatically create the flyweights that are not present in the list,
// and also generate a count of the total flyweights in the list
const CharacterFlyweightFactory = (function () {
   const flyweights = {}

   return {
   	get: function (value, type) {
       	if (flyweights[value + type] === undefined)
           	flyweights[value + type] = new CharacterFlyweight(value, type)

       	return flyweights[value + type]
   	},
   	count: function () {
       	let count = 0;
       	for (var f in flyweights) count++;
       	return count;
   	}
   }
})()

// An enhanced Character class that uses flyweights to store references
// to recurring value and type combinations
function CharacterWithFlyweight(value, type, position) {
   this.flyweight = CharacterFlyweightFactory.get(value, type)
   this.position = position
}

// A helper function to define the type of a character
// It identifies numbers as N and everything as A (for alphabets)
function getCharacterType(char) {
   switch (char) {
   	case "0":
   	case "1":
   	case "2":
   	case "3":
   	case "4":
   	case "5":
   	case "6":
   	case "7":
   	case "8":
   	case "9": return "N"
   	default:
       	return "A"

   }
}

// A list class to create an array of Characters from a given string
function CharactersList(str) {
   chars = []
   for (let i = 0; i < str.length; i++) {
   	const char = str[i]
   	chars.push(new Character(char, getCharacterType(char), i))
   }

   return chars
}

// A list class to create an array of CharacterWithFlyweights from a given string
function CharactersWithFlyweightsList(str) {
   chars = []
   for (let i = 0; i  " + charactersList.length)
   // Output: Character count -> 656

   // The number of flyweights created is only 31, since only 31 characters are used to write the
   // entire paragraph. This means that to store 656 characters, a total of
   // (31 * 2 + 656 * 1 = 718) memory blocks are used instead of (656 * 3 = 1968) which would have
   // used by the standard array.
   // (We have assumed each variable to take up one memory block for simplicity. This
   // may vary in real-life scenarios)
   console.log("Flyweights created -> " + CharacterFlyweightFactory.count())
   // Output: Flyweights created -> 31

}

run()

Come avrete già notato, il pattern Flyweight aumenta la complessità del progetto del vostro software e non è particolarmente intuitivo. Quindi, se il risparmio di memoria non è un problema urgente per la vostra applicazione, la complessità aggiuntiva di Flyweight può essere più dannosa che positiva.

Inoltre, i flyweight scambiano la memoria con l’efficienza di elaborazione, quindi se siete a corto di cicli di CPU, Flyweight non è una buona soluzione per voi.

12. Proxy

Lo schema Proxy vi aiuta a sostituire un oggetto con un altro. In altre parole, gli oggetti proxy possono prendere il posto degli oggetti reali (di cui sono un proxy) e controllare l’accesso all’oggetto. Questi oggetti proxy possono essere utilizzati per eseguire alcune azioni prima o dopo che la richiesta di invocazione sia passata all’oggetto reale.

Nell’esempio che segue, vedrete come l’accesso a un’istanza di database viene controllato tramite un proxy che esegue alcuni controlli di convalida di base sulle richieste prima di lasciarle passare:

function DatabaseHandler() {
   const data = {}

   this.set = function (key, val) {
   	data[key] = val;
   }
   this.get = function (key, val) {
   	return data[key]
   }
   this.remove = function (key) {
   	data[key] = null;
   }


}

function DatabaseProxy(databaseInstance) {

   this.set = function (key, val) {
   	if (key === "") {
       	console.log("Invalid input")
       	return
   	}

   	if (val === undefined) {
       	console.log("Setting value to undefined not allowed!")
       	return
   	}

   	databaseInstance.set(key, val)
   }

   this.get = function (key) {
   	if (databaseInstance.get(key) === null) {
       	console.log("Element deleted")
   	}

   	if (databaseInstance.get(key) === undefined) {
       	console.log("Element not created")
   	}

   	return databaseInstance.get(key)
   }

   this.remove = function (key) {
   	if (databaseInstance.get(key) === undefined) {
       	console.log("Element not added")
       	return
   	}

   	if (databaseInstance.get(key) === null) {
       	console.log("Element removed already")
       	return
   	}

   	return databaseInstance.remove(key)
   }

}

function run() {
   let databaseInstance = new DatabaseHandler()

   databaseInstance.set("foo," "bar")
   databaseInstance.set("foo," undefined)
   console.log("#1: " + databaseInstance.get("foo"))
   // #1: undefined

   console.log("#2: " + databaseInstance.get("baz"))
   // #2: undefined

   databaseInstance.set("," "something")

   databaseInstance.remove("foo")
   console.log("#3: " + databaseInstance.get("foo"))
   // #3: null

   databaseInstance.remove("foo")
   databaseInstance.remove("baz")

   // Create a fresh database instance to try the same operations
   // using the proxy
   databaseInstance = new DatabaseHandler()
   let proxy = new DatabaseProxy(databaseInstance)

   proxy.set("foo," "bar")
   proxy.set("foo," undefined)
   // Proxy jumps in:
   // Output: Setting value to undefined not allowed!

   console.log("#1: " + proxy.get("foo"))
   // Original value is retained:
   // Output: #1: bar

   console.log("#2: " + proxy.get("baz"))
   // Proxy jumps in again
   // Output:
   // Element not created
   // #2: undefined


   proxy.set("," "something")
   // Proxy jumps in again
   // Output: Invalid input

   proxy.remove("foo")

   console.log("#3: " + proxy.get("foo"))
   // Proxy jumps in again
   // Output:
   // Element deleted
   // #3: null

   proxy.remove("foo")
   // Proxy output: Element removed already
   proxy.remove("baz")
   // Proxy output: Element not added

}

run()

Questo design pattern è comunemente utilizzato in tutto il settore e aiuta a implementare facilmente le operazioni di pre-esecuzione e post-esecuzione. Tuttavia, come ogni altro design pattern, aggiunge complessità alla vostra codebase, quindi cercate di non usarlo se non ne avete davvero bisogno.

Dovrete anche tenere presente che, poiché viene coinvolto un oggetto aggiuntivo quando si effettuano le chiamate al vostro oggetto reale, potrebbe esserci una certa latenza dovuta alle operazioni di elaborazione aggiunte. L’ottimizzazione delle prestazioni dell’oggetto principale comporta anche l’ottimizzazione dei metodi del proxy.

Comportamentali

I design pattern comportamentali aiutano a risolvere i problemi legati all’interazione tra gli oggetti. Questo può comportare la condivisione o il passaggio di responsabilità/controllo tra gli oggetti per completare le operazioni. Può anche riguardare il passaggio/condivisione di dati tra più oggetti nel modo più efficiente possibile.

13. Chain of Responsibility

Il pattern Chain of Responsibility è uno dei design pattern comportamentali più semplici. Si rivela utile quando si progetta la logica per operazioni che possono essere gestite da più gestori.

In modo simile a come funziona l’escalation dei problemi nei team di assistenza, il controllo passa attraverso una catena di gestori e il gestore responsabile dell’azione completa l’operazione. Questo schema di progettazione è spesso utilizzato nella progettazione delle interfacce utente, dove più livelli di componenti possono gestire un evento di input dell’utente, come un tocco o uno scorrimento.

Qui di seguito potete vedere un esempio di escalation di un reclamo che utilizza il modello della Chain of Responsibility. Il reclamo verrà gestito dai gestori in base alla sua gravità:

// Complaint class that stores title and severity of a complaint
// Higher value of severity indicates a more severe complaint
function Complaint (title, severity) {
	this.title = title
	this.severity = severity
}

// Base level handler that receives all complaints
function Representative () {
	// If this handler can not handle the complaint, it will be forwarded to the next level
	this.nextLevel = new Management()

	this.handleComplaint = function (complaint) {
    	if (complaint.severity === 0)
        	console.log("Representative resolved the following complaint: " + complaint.title)
    	else
        	this.nextLevel.handleComplaint(complaint)
	}
}

// Second level handler to handle complaints of severity 1
function Management() {
	// If this handler can not handle the complaint, it will be forwarded to the next level
	this.nextLevel = new Leadership()

	this.handleComplaint = function (complaint) {
    	if (complaint.severity === 1)
        	console.log("Management resolved the following complaint: " + complaint.title)
    	else
        	this.nextLevel.handleComplaint(complaint)
	}
}

// Highest level handler that handles all complaints unhandled so far
function Leadership() {
	this.handleComplaint = function (complaint) {
    	console.log("Leadership resolved the following complaint: " + complaint.title)
	}
}

function run() {
	// Create an instance of the base level handler
	let customerSupport = new Representative()

	// Create multiple complaints of varying severity and pass them to the base handler

	let complaint1 = new Complaint("Submit button doesn't work," 0)
	customerSupport.handleComplaint(complaint1)
	// Output: Representative resolved the following complaint: Submit button doesn't work

	let complaint2 = new Complaint("Payment failed," 1)
	customerSupport.handleComplaint(complaint2)
	// Output: Management resolved the following complaint: Payment failed

	let complaint3 = new Complaint("Employee misdemeanour," 2)
	customerSupport.handleComplaint(complaint3)
	// Output: Leadership resolved the following complaint: Employee misdemeanour
}

run()

L’ovvio problema di questa struttura è che è lineare, quindi può esserci una certa latenza nella gestione di un’operazione quando un gran numero di gestori sono concatenati l’uno all’altro.

Tenere traccia di tutti i gestori può essere un altro punto dolente, perché dopo un certo numero le cose possono farsi molto disordinate. Il debug è un altro grattacapo, perché ogni richiesta può terminare con un gestore diverso, rendendo difficile standardizzare il processo di log e debug.

14. Iterator

Il pattern Iterator è piuttosto semplice ed è molto utilizzato in quasi tutti i moderni linguaggi orientati agli oggetti. Se vi trovate a dover scorrere un elenco di oggetti che non sono tutti dello stesso tipo, i normali metodi di iterazione, come i loop for, possono diventare piuttosto complicati, soprattutto se al loro interno scrivete anche della logica aziendale.

Il pattern Iterator può aiutarvi a isolare la logica di iterazione e di elaborazione degli elenchi dalla logica aziendale principale.

Ecco come potete usarlo per un elenco di base con più tipi di elementi:

// Iterator for a complex list with custom methods
function Iterator(list) {
   this.list = list
   this.index = 0

   // Fetch the current element
   this.current = function() {
   	return this.list[this.index]
   }

   // Fetch the next element in the list
   this.next = function() {
   	return this.list[this.index++]
   }

   // Check if there is another element in the list
   this.hasNext = function() {
   	return this.index < this.list.length
   }

   // Reset the index to point to the initial element
   this.resetIndex = function() {
   	this.index = 0
   }

   // Run a forEach loop over the list
   this.forEach = function(callback) {
   	for (let element = this.next(); this.index <= this.list.length; element = this.next()) {
       	callback(element)
   	}
   }
}

function run() {
   // A complex list with elements of multiple data types
   let list = ["Lorem ipsum," 9, ["lorem ipsum dolor," true], false]

   // Create an instance of the iterator and pass it the list
   let iterator = new Iterator(list)

   // Log the first element
   console.log(iterator.current())
   // Output: Lorem ipsum

   // Print all elements of the list using the iterator's methods
   while (iterator.hasNext()) {
   	console.log(iterator.next())
   	/**
    	* Output:
    	* Lorem ipsum
    	* 9
    	* [ 'lorem ipsum dolor', true ]
    	* false
    	*/
   }

   // Reset the iterator's index to the first element
   iterator.resetIndex()

   // Use the custom iterator to pass an effect that will run for each element of the list
   iterator.forEach(function (element) {
   	console.log(element)
   })
   /**
	* Output:
	* Lorem ipsum
	* 9
	* [ 'lorem ipsum dolor', true ]
	* false
	*/
}

run()

Inutile dire che questo schema può essere inutilmente complesso per gli elenchi senza più tipi di elementi. Inoltre, se ci sono troppi tipi di elementi in un elenco, può diventare difficile da gestire.

Il segreto è capire se avete davvero bisogno di un iteratore in base alla vostra lista e alle sue possibilità di modifica futura. Inoltre, lo schema dell’iteratore è utile solo per gli elenchi e gli elenchi possono talvolta limitarvi alla loro modalità di accesso lineare. Altre strutture di dati possono offrire maggiori vantaggi in termini di prestazioni.

15. Mediator

Il progetto della vostra applicazione può richiedere di giocare con un gran numero di oggetti distinti che ospitano vari tipi di logica aziendale e che spesso dipendono l’uno dall’altro. La gestione delle dipendenze può essere a volte complicata perché dovete tenere traccia di come questi oggetti si scambiano dati e controlli tra loro.

Il design pattern Mediator vi aiuta a risolvere questo problema isolando la logica di interazione di questi oggetti in un oggetto separato.

Questo oggetto separato è noto come mediatore ed è responsabile del lavoro svolto dalle classi di livello inferiore. Anche il vostro cliente o l’ambiente chiamante interagirà con il mediatore invece che con le classi di livello inferiore.

Ecco un esempio del design pattern Mediator in azione:

// Writer class that receives an assignment, writes it in 2 seconds, and marks it as finished
function Writer(name, manager) {
    
	// Reference to the manager, writer's name, and a busy flag that the manager uses while assigning the article
	this.manager = manager
	this.name = name
	this.busy = false

	this.startWriting = function (assignment) {
    	console.log(this.name + " started writing "" + assignment + """)
    	this.assignment = assignment
    	this.busy = true

    	// 2 s timer to replicate manual action
    	setTimeout(() => { this.finishWriting() }, 2000)
	}

	this.finishWriting = function () {
    	if (this.busy === true) {
        	console.log(this.name + " finished writing "" + this.assignment + """)
        	this.busy = false
        	return this.manager.notifyWritingComplete(this.assignment)
    	} else {
        	console.log(this.name + " is not writing any article")
    	}
	}
}

// Editor class that receives an assignment, edits it in 3 seconds, and marks it as finished
function Editor(name, manager) {
    
	// Reference to the manager, writer's name, and a busy flag that the manager uses while assigning the article
	this.manager = manager
	this.name = name
	this.busy = false

	this.startEditing = function (assignment) {
    	console.log(this.name + " started editing "" + assignment + """)
    	this.assignment = assignment
    	this.busy = true

    	// 3 s timer to replicate manual action
    	setTimeout(() => { this.finishEditing() }, 3000)
	}

	this.finishEditing = function () {
    	if (this.busy === true) {
        	console.log(this.name + " finished editing "" + this.assignment + """)
        	this.manager.notifyEditingComplete(this.assignment)
        	this.busy = false
    	} else {
        	console.log(this.name + " is not editing any article")
    	}
	}
}

// The mediator class
function Manager() {
	// Store arrays of workers
	this.editors = []
	this.writers = []

	this.setEditors = function (editors) {
    	this.editors = editors
	}
	this.setWriters = function (writers) {
    	this.writers = writers
	}

	// Manager receives new assignments via this method
	this.notifyNewAssignment = function (assignment) {
    	let availableWriter = this.writers.find(function (writer) {
        	return writer.busy === false
    	})
    	availableWriter.startWriting(assignment)
    	return availableWriter
	}

	// Writers call this method to notify they're done writing
	this.notifyWritingComplete = function (assignment) {
    	let availableEditor = this.editors.find(function (editor) {
        	return editor.busy === false
    	})
    	availableEditor.startEditing(assignment)
    	return availableEditor
	}

	// Editors call this method to notify they're done editing
	this.notifyEditingComplete = function (assignment) {
    	console.log(""" + assignment + "" is ready to publish")
	}

}

function run() {
	// Create a manager
	let manager = new Manager()

	// Create workers
	let editors = [
    	new Editor("Ed," manager),
    	new Editor("Phil," manager),
	]

	let writers = [
    	new Writer("Michael," manager),
    	new Writer("Rick," manager),
	]

	// Attach workers to manager
	manager.setEditors(editors)
	manager.setWriters(writers)

	// Send two assignments to manager
	manager.notifyNewAssignment("var vs let in JavaScript")
	manager.notifyNewAssignment("JS promises")

	/**
 	* Output:
 	* Michael started writing "var vs let in JavaScript"
 	* Rick started writing "JS promises"
 	*
 	* After 2s, output:
 	* Michael finished writing "var vs let in JavaScript"
 	* Ed started editing "var vs let in JavaScript"
 	* Rick finished writing "JS promises"
 	* Phil started editing "JS promises"
 	*
 	* After 3s, output:
 	* Ed finished editing "var vs let in JavaScript"
 	* "var vs let in JavaScript" is ready to publish
 	* Phil finished editing "JS promises"
 	* "JS promises" is ready to publish
 	*/

}

run()

Sebbene il mediatore fornisca al progetto della vostra applicazione un disaccoppiamento e una grande flessibilità, alla fine fine è un’altra classe che dovete mantenere. Dovete valutare se il vostro progetto può davvero trarre beneficio da un mediatore prima di scriverne uno, in modo da non finire per aggiungere inutili complessità alla vostra code base.

Inoltre, è importante tenere presente che anche se la classe del mediatore non contiene alcuna logica aziendale diretta, contiene comunque molto codice fondamentale per il funzionamento della vostra applicazione e può quindi complicarsi rapidamente.

16. Memento

Il versioning degli oggetti è un altro problema comune che si incontra quando si sviluppano applicazioni. Ci sono molti casi d’uso in cui è necessario mantenere la cronologia di un oggetto, supportare un facile rollback e, a volte, anche il ripristino di tali rollback. Scrivere la logica per queste applicazioni può essere complicato.

Il design pattern Memento è pensato per risolvere facilmente questo problema.

Un memento è un’istantanea di un oggetto in un determinato momento. Il design pattern Memento utilizza questi memento per conservare le istantanee dell’oggetto mentre viene modificato nel tempo. Quando avete bisogno di tornare a una vecchia versione, potete semplicemente recuperare il memento.

Ecco come implementarlo in un’applicazione per l’elaborazione del testo:

// The memento class that can hold one snapshot of the Originator class - document
function Text(contents) {
	// Contents of the document
	this.contents = contents

	// Accessor function for contents
	this.getContents = function () {
    	return this.contents
	}

	// Helper function to calculate word count for the current document
	this.getWordCount = function () {
    	return this.contents.length
	}
}

// The originator class that holds the latest version of the document
function Document(contents) {
	// Holder for the memento, i.e., the text of the document
	this.text = new Text(contents)

	// Function to save new contents as a memento
	this.save = function (contents) {
    	this.text = new Text(contents)
    	return this.text
	}

	// Function to revert to an older version of the text using a memento
	this.restore = function (text) {
    	this.text = new Text(text.getContents())
	}

	// Helper function to get the current memento
	this.getText = function () {
    	return this.text
	}

	// Helper function to get the word count of the current document
	this.getWordCount = function () {
    	return this.text.getWordCount()
	}
}

// The caretaker class that providers helper functions to modify the document
function DocumentManager(document) {
	// Holder for the originator, i.e., the document
	this.document = document

	// Array to maintain a list of mementos
	this.history = []

	// Add the initial state of the document as the first version of the document
	this.history.push(document.getText())

	// Helper function to get the current contents of the documents
	this.getContents = function () {
    	return this.document.getText().getContents()
	}

	// Helper function to get the total number of versions available for the document
	this.getVersionCount = function () {
    	return this.history.length
	}

	// Helper function to get the complete history of the document
	this.getHistory = function () {
    	return this.history.map(function (element) {
        	return element.getContents()
    	})

	}

	// Function to overwrite the contents of the document
	this.overwrite = function (contents) {
    	let newVersion = this.document.save(contents)
    	this.history.push(newVersion)
	}

	// Function to append new content to the existing contents of the document
	this.append = function (contents) {
    	let currentVersion = this.history[this.history.length - 1]
    	let newVersion
    	if (currentVersion === undefined)
        	newVersion = this.document.save(contents)
    	else
        	newVersion = this.document.save(currentVersion.getContents() + contents)
    	this.history.push(newVersion)
	}

	// Function to delete all the contents of the document
	this.delete = function () {
    	this.history.push(this.document.save(""))
	}

	// Function to get a particular version of the document
	this.getVersion = function (versionNumber) {
    	return this.history[versionNumber - 1]
	}

	// Function to undo the last change
	this.undo = function () {
    	let previousVersion = this.history[this.history.length - 2]
    	this.document.restore(previousVersion)
    	this.history.push(previousVersion)
	}

	// Function to revert the document to a previous version
	this.revertToVersion = function (version) {
    	let previousVersion = this.history[version - 1]
    	this.document.restore(previousVersion)
    	this.history.push(previousVersion)
	}

	// Helper function to get the total word count of the document
	this.getWordCount = function () {
    	return this.document.getWordCount()
	}

}

function run() {
	// Create a document
	let blogPost = new Document("")

	// Create a caretaker for the document
	let blogPostManager = new DocumentManager(blogPost)

	// Change #1: Add some text
	blogPostManager.append("Hello World!")
	console.log(blogPostManager.getContents())
	// Output: Hello World!

	// Change #2: Add some more text
	blogPostManager.append(" This is the second entry in the document")
	console.log(blogPostManager.getContents())
	// Output: Hello World! This is the second entry in the document

	// Change #3: Overwrite the document with some new text
	blogPostManager.overwrite("This entry overwrites everything in the document")
	console.log(blogPostManager.getContents())
	// Output: This entry overwrites everything in the document

	// Change #4: Delete the contents of the document
	blogPostManager.delete()
	console.log(blogPostManager.getContents())
	// Empty output

	// Get an old version of the document
	console.log(blogPostManager.getVersion(2).getContents())
	// Output: Hello World!

	// Change #5: Go back to an old version of the document
	blogPostManager.revertToVersion(3)
	console.log(blogPostManager.getContents())
	// Output: Hello World! This is the second entry in the document

	// Get the word count of the current document
	console.log(blogPostManager.getWordCount())
	// Output: 53

	// Change #6: Undo the last change
	blogPostManager.undo()
	console.log(blogPostManager.getContents())
	// Empty output

	// Get the total number of versions for the document
	console.log(blogPostManager.getVersionCount())
	// Output: 7

	// Get the complete history of the document
	console.log(blogPostManager.getHistory())
	/**
 	* Output:
 	* [
 	*   '',
 	*   'Hello World!',
 	*   'Hello World! This is the second entry in the document',
 	*   'This entry overwrites everything in the document',
 	*   '',
 	*   'Hello World! This is the second entry in the document',
 	*   ''
 	* ]
 	*/
}

run()

Sebbene il design pattern Memento sia un’ottima soluzione per gestire la cronologia di un oggetto, può richiedere molte risorse. Dal momento che ogni memento è quasi una copia dell’oggetto, può appesantire la memoria dell’applicazione molto rapidamente se non viene usato con moderazione.

Con un gran numero di oggetti, anche la gestione del loro ciclo di vita può diventare un compito piuttosto noioso. Inoltre, le classi Originator e Caretaker sono di solito strettamente accoppiate, il che aumenta la complessità della vostra codebase.

17. Observer

Il pattern Observer fornisce una soluzione alternativa al problema dell’interazione tra più oggetti (già visto nel pattern Mediator).

Invece di permettere a ogni oggetto di comunicare tra loro attraverso un mediatore designato, il pattern Observer permette agli oggetti di osservarsi a vicenda. Gli oggetti sono progettati per emettere eventi quando cercano di inviare dati o controlli e gli altri oggetti che sono in “ascolto” di questi eventi possono riceverli e interagire in base al loro contenuto.

Ecco una semplice dimostrazione dell’invio di newsletter a più persone attraverso il pattern Observer:

// The newsletter class that can send out posts to its subscribers
function Newsletter() {
   // Maintain a list of subscribers
   this.subscribers = []

   // Subscribe a reader by adding them to the subscribers' list
   this.subscribe = function(subscriber) {
   	this.subscribers.push(subscriber)
   }

   // Unsubscribe a reader by removing them from the subscribers' list
   this.unsubscribe = function(subscriber) {
   	this.subscribers = this.subscribers.filter(
       	function (element) {
           	if (element !== subscriber) return element
       	}
   	)
   }

   // Publish a post by calling the receive function of all subscribers
   this.publish = function(post) {
   	this.subscribers.forEach(function(element) {
       	element.receiveNewsletter(post)
   	})
   }
}

// The reader class that can subscribe to and receive updates from newsletters
function Reader(name) {
   this.name = name

   this.receiveNewsletter = function(post) {
   	console.log("Newsletter received by " + name + "!: " + post)
   }

}

function run() {
   // Create two readers
   let rick = new Reader("ed")
   let morty = new Reader("morty")

   // Create your newsletter
   let newsletter = new Newsletter()

   // Subscribe a reader to the newsletter
   newsletter.subscribe(rick)

   // Publish the first post
   newsletter.publish("This is the first of the many posts in this newsletter")
   /**
	* Output:
	* Newsletter received by ed!: This is the first of the many posts in this newsletter
	*/

   // Subscribe another reader to the newsletter
   newsletter.subscribe(morty)

   // Publish the second post
   newsletter.publish("This is the second of the many posts in this newsletter")
   /**
	* Output:
	* Newsletter received by ed!: This is the second of the many posts in this newsletter
	* Newsletter received by morty!: This is the second of the many posts in this newsletter
	*/

   // Unsubscribe the first reader
   newsletter.unsubscribe(rick)

   // Publish the third post
   newsletter.publish("This is the third of the many posts in this newsletter")
   /**
	* Output:
	* Newsletter received by morty!: This is the third of the many posts in this newsletter
	*/

}

run()

Sebbene il pattern Observer sia un modo elegante di trasmettere controllo e dati, è più adatto a situazioni in cui ci sono molti mittenti e destinatari che interagiscono tra loro attraverso un numero limitato di connessioni. Se gli oggetti dovessero tutti effettuare connessioni uno a uno, perdereste il vantaggio che si ottiene pubblicando e sottoscrivendo eventi, poiché ci sarà sempre un solo sottoscrittore per ogni editore (mentre sarebbe stato meglio gestire una linea di comunicazione diretta tra di loro).

Inoltre, il design pattern Observer può causare problemi di prestazioni se gli eventi di sottoscrizione non vengono gestiti correttamente. Se un oggetto continua a sottoscrivere un altro oggetto anche quando non ne ha bisogno, non potrà essere sottoposto a garbage collection e aumenterà il consumo di memoria dell’applicazione.

18. State

Il design pattern State è uno dei più utilizzati nel settore dello sviluppo software. I framework JavaScript più diffusi, come React e Angular, si basano molto sul pattern State per gestire i dati e il comportamento dell’applicazione in base a tali dati.

In parole povere, il design pattern State è utile nelle situazioni in cui è possibile definire gli stati definitivi di un’entità (che può essere un componente, una pagina, un’applicazione o una macchina) e l’entità ha una reazione predefinita al cambiamento di stato.

Supponiamo che stiate cercando di creare un processo di richiesta di un prestito. Ogni fase del processo di richiesta può essere definita come uno stato.

Mentre il cliente di solito vede un piccolo elenco di stati semplificati della sua domanda (in attesa, in revisione, accettata e rifiutata), ci possono essere altri passaggi coinvolti internamente. In ognuna di queste fasi, la domanda viene assegnata a una persona diversa e può avere requisiti unici.

Il sistema è progettato in modo tale che al termine dell’elaborazione di uno stato, questo venga aggiornato a quello successivo e venga avviata la successiva serie di passaggi.

Ecco come potete costruire un sistema di gestione delle attività utilizzando il design pattern State:

// Create titles for all states of a task
const STATE_TODO = "TODO"
const STATE_IN_PROGRESS = "IN_PROGRESS"
const STATE_READY_FOR_REVIEW = "READY_FOR_REVIEW"
const STATE_DONE = "DONE"

// Create the task class with a title, assignee, and duration of the task
function Task(title, assignee) {
	this.title = title
	this.assignee = assignee

	// Helper function to update the assignee of the task
	this.setAssignee = function (assignee) {
    	this.assignee = assignee
	}

	// Function to update the state of the task
	this.updateState = function (state) {

    	switch (state) {
        	case STATE_TODO:
            	this.state = new TODO(this)
            	break
        	case STATE_IN_PROGRESS:
            	this.state = new IN_PROGRESS(this)
            	break
        	case STATE_READY_FOR_REVIEW:
            	this.state = new READY_FOR_REVIEW(this)
            	break
        	case STATE_DONE:
            	this.state = new DONE(this)
            	break
        	default:
            	return
    	}
    	// Invoke the callback function for the new state after it is set
    	this.state.onStateSet()
	}

	// Set the initial state of the task as TODO
	this.updateState(STATE_TODO)
}

// TODO state
function TODO(task) {

	this.onStateSet = function () {
    	console.log(task.assignee + " notified about new task "" + task.title + """)
	}
}

// IN_PROGRESS state
function IN_PROGRESS(task) {

	this.onStateSet = function () {
    	console.log(task.assignee + " started working on the task "" + task.title + """)
	}
}

// READY_FOR_REVIEW state that updates the assignee of the task to be the manager of the developer
// for the review
function READY_FOR_REVIEW(task) {
	this.getAssignee = function () {
    	return "Manager 1"
	}

	this.onStateSet = function () {
    	task.setAssignee(this.getAssignee())
    	console.log(task.assignee + " notified about completed task "" + task.title + """)
	}
}

// DONE state that removes the assignee of the task since it is now completed
function DONE(task) {
	this.getAssignee = function () {
    	return ""
	}

	this.onStateSet = function () {
    	task.setAssignee(this.getAssignee())
    	console.log("Task "" + task.title + "" completed")
	}
}

function run() {
	// Create a task
	let task1 = new Task("Create a login page," "Developer 1")
	// Output: Developer 1 notified about new task "Create a login page"

	// Set it to IN_PROGRESS
	task1.updateState(STATE_IN_PROGRESS)
	// Output: Developer 1 started working on the task "Create a login page"

	// Create another task
	let task2 = new Task("Create an auth server," "Developer 2")
	// Output: Developer 2 notified about new task "Create an auth server"


	// Set it to IN_PROGRESS as well
	task2.updateState(STATE_IN_PROGRESS)
	// Output: Developer 2 started working on the task "Create an auth server"

	// Update the states of the tasks until they are done
	task2.updateState(STATE_READY_FOR_REVIEW)
	// Output: Manager 1 notified about completed task "Create an auth server"
	task1.updateState(STATE_READY_FOR_REVIEW)
	// Output: Manager 1 notified about completed task "Create a login page"


	task1.updateState(STATE_DONE)
	// Output: Task "Create a login page" completed
	task2.updateState(STATE_DONE)
	// Output: Task "Create an auth server" completed

}

run()

Sebbene il pattern State faccia un ottimo lavoro di separazione delle fasi di un processo, può diventare estremamente difficile da mantenere in applicazioni di grandi dimensioni che hanno più stati.

Inoltre, se il design del vostro processo non prevede solo un movimento lineare attraverso tutti gli stati, dovrete scrivere e mantenere più codice, poiché ogni transizione di stato deve essere gestita separatamente.

19. Strategy

Conosciuto anche come pattern Policy, il pattern Strategy ha lo scopo di aiutarvi a incapsulare e scambiare liberamente le classi utilizzando un’interfaccia comune. Questo aiuta a mantenere un basso accoppiamento tra il client e le classi e vi permette di aggiungere tutte le implementazioni che desiderate.

Il pattern Strategy è noto per essere di grande aiuto nelle situazioni in cui è necessario eseguire la stessa operazione con metodi/algoritmi diversi o in cui è necessario sostituire blocchi di commutazione massicci con codice più semplice da utilizzare.

Ecco un esempio del pattern Strategy:

// The strategy class that can encapsulate all hosting providers
function HostingProvider() {
   // store the provider
   this.provider = ""

   // set the provider
   this.setProvider = function(provider) {
   	this.provider = provider
   }

   // set the website configuration for which each hosting provider would calculate costs
   this.setConfiguration = function(configuration) {
   	this.configuration = configuration
   }

   // the generic estimate method that calls the provider's unique methods to calculate the costs
   this.estimateMonthlyCost = function() {
   	return this.provider.estimateMonthlyCost(this.configuration)
   }
}

// Foo Hosting charges for each second and KB of hosting usage
function FooHosting (){
   this.name = "FooHosting"
   this.rate = 0.0000027

   this.estimateMonthlyCost = function(configuration){
   	return configuration.duration * configuration.workloadSize * this.rate
   }
}

// Bar Hosting charges per minute instead of seconds
function BarHosting (){
   this.name = "BarHosting"
   this.rate = 0.00018

   this.estimateMonthlyCost = function(configuration){
   	return configuration.duration / 60 * configuration.workloadSize * this.rate
   }
}

// Baz Hosting assumes the average workload to be of 10 MB in size
function BazHosting (){
   this.name = "BazHosting"
   this.rate = 0.032

   this.estimateMonthlyCost = function(configuration){
   	return configuration.duration * this.rate
   }
}

function run() {

   // Create a website configuration for a website that is up for 24 hours and takes 10 MB of hosting space
   let workloadConfiguration = {
   	duration: 84700,
   	workloadSize: 10240
   }

   // Create the hosting provider instances
   let fooHosting = new FooHosting()
   let barHosting = new BarHosting()
   let bazHosting = new BazHosting()

   // Create the instance of the strategy class
   let hostingProvider = new HostingProvider()

   // Set the configuration against which the rates have to be calculated
   hostingProvider.setConfiguration(workloadConfiguration)

   // Set each provider one by one and print the rates
   hostingProvider.setProvider(fooHosting)
   console.log("FooHosting cost: " + hostingProvider.estimateMonthlyCost())
   // Output: FooHosting cost: 2341.7856

   hostingProvider.setProvider(barHosting)
   console.log("BarHosting cost: " + hostingProvider.estimateMonthlyCost())
   // Output: BarHosting cost: 2601.9840

   hostingProvider.setProvider(bazHosting)
   console.log("BarHosting cost: " + hostingProvider.estimateMonthlyCost())
   // Output: BarHosting cost: 2710.4000

}

run()

Il pattern Strategy è ottimo quando si tratta di introdurre nuove varianti di un’entità senza modificare più di tanto i client. Tuttavia, può sembrare eccessivo se avete solo una manciata di varianti da implementare.

Inoltre, l’incapsulamento elimina i dettagli più fini della logica interna di ogni variante, per cui il cliente non sa come si comporterà una variante.

20. Visitor

Il pattern Visitor vi aiuta a rendere il vostro codice estensibile.

L’idea è quella di fornire un metodo nella classe che permetta agli oggetti di altre classi di apportare facilmente modifiche agli oggetti della classe corrente. Gli altri oggetti visitano l’oggetto corrente (chiamato anche oggetto luogo), oppure la classe corrente accetta gli oggetti visitatori e l’oggetto luogo gestisce la visita di ogni oggetto esterno in modo appropriato.

Ecco come usarlo:

// Visitor class that defines the methods to be called when visiting each place
function Reader(name, cash) {
	this.name = name
	this.cash = cash

	// The visit methods can access the place object and invoke available functions
	this.visitBookstore = function(bookstore) {
    	console.log(this.name + " visited the bookstore and bought a book")
    	bookstore.purchaseBook(this)
	}

	this.visitLibrary = function() {
    	console.log(this.name + " visited the library and read a book")
	}

	// Helper function to demonstrate a transaction
	this.pay = function(amount) {
    	this.cash -= amount
	}
}

// Place class for a library
function Library () {
	this.accept = function(reader) {
    	reader.visitLibrary()
	}
}

// Place class for a bookstore that allows purchasing book
function Bookstore () {
	this.accept = function(reader) {
    	reader.visitBookstore(this)
	}

	this.purchaseBook = function (visitor) {
    	console.log(visitor.name + " bought a book")
    	visitor.pay(8)
	}
}


function run() {
	// Create a reader (the visitor)
	let reader = new Reader("Rick," 30)

	// Create the places
	let booksInc = new Bookstore()
	let publicLibrary = new Library()

	// The reader visits the library
	publicLibrary.accept(reader)
	// Output: Rick visited the library and read a book
	console.log(reader.name + " has $" + reader.cash)
	// Output: Rick has $30

	// The reader visits the bookstore
	booksInc.accept(reader)
	// Output: Rick visited the bookstore and bought a book
	console.log(reader.name + " has $" + reader.cash)
	// Output: Rick has $22
}

run()

L’unico difetto di questo design è che ogni classe visitatore deve essere aggiornata ogni volta che viene aggiunto o modificato un nuovo luogo. Nei casi in cui esistono più visitatori e oggetti luogo insieme, può essere difficile da mantenere.

A parte questo, il metodo funziona benissimo per migliorare la funzionalità delle classi in modo dinamico.

Le Migliori Pratiche per Implementare i Design Pattern

Ora che avete visto i design pattern più comuni in JavaScript, ecco alcuni consigli che dovreste tenere a mente quando li implementate.

Prestare Particolare Attenzione a Capire Se un Modello Si Adatta alla Soluzione

Questo consiglio va applicato prima di implementare un design pattern nel vostro codice sorgente. Anche se può sembrare che un design pattern sia la fine di tutte le vostre preoccupazioni, prendetevi un momento per analizzare criticamente se questo è vero.

Ci sono molti modelli che risolvono lo stesso problema ma con approcci diversi e conseguenze diverse. Quindi il criterio di selezione di un design pattern non dovrebbe essere solo se risolve o meno il vostro problema, ma anche quanto bene lo risolve e se c’è qualche altro pattern che può presentare una soluzione più efficiente.

Comprendere i Costi dell’Implementazione di un Pattern Prima di Iniziare

Anche se i design pattern sembrano essere la soluzione migliore per tutti i problemi ingegneristici, non dovreste lanciarvi subito nell’implementazione nel vostro codice sorgente.

Nel valutare le conseguenze dell’implementazione di una soluzione, dovete prendere in considerazione anche la vostra situazione. Avete un team di sviluppo software numeroso con persone esperte nella comprensione e nella manutenzione dei design pattern? Oppure siete nella fase iniziale della vostra attività con un team di sviluppo minimo e volete rilasciare un MVP veloce del vostro prodotto? Se la risposta all’ultima domanda è sì, i design pattern potrebbero non essere il metodo di sviluppo più adatto a voi.

I design pattern non portano a un riutilizzo massiccio del codice a meno che non siano pianificati in una fase molto precoce della progettazione dell’applicazione. L’utilizzo casuale dei design pattern in varie fasi può portare a un’architettura dell’app inutilmente complessa che dovrete semplificare per settimane.

L’efficacia di un design pattern non può essere giudicata da alcuna forma di test. Saranno l’esperienza e l’introspezione del team a farvi capire se funzionano. Se avete il tempo e le risorse da dedicare a questi aspetti, solo allora i design pattern risolveranno davvero i vostri problemi.

Non Trasformare Ogni Soluzione in un Modello

Un’altra regola da tenere a mente è quella di non cercare di trasformare ogni piccolo problema-soluzione in un design pattern e di utilizzarlo ovunque ci sia spazio per esso.

Anche se è bene identificare soluzioni standard e tenerle a mente quando si incontrano problemi simili, è molto probabile che il nuovo problema incontrato non corrisponda esattamente alla stessa descrizione di un problema precedente. In questo caso, potreste finire per implementare una soluzione non ottimale e sprecare risorse.

I design pattern si sono affermati oggi come esempi principali di coppie problema-soluzione perché sono stati testati da centinaia e migliaia di programmatori nel corso del tempo e sono stati generalizzati il più possibile. Se cercate di replicare questo sforzo limitandovi a esaminare un gruppo di problemi e soluzioni e a definirli simili, potreste finire per danneggiare il vostro codice molto più di quanto vi sareste mai aspettati.

Quando Usare i Design Pattern?

Per riassumere, ecco alcuni spunti che dovreste tenere in considerazione per usare i design pattern. Non tutti si applicano allo sviluppo di ogni applicazione, ma dovrebbero darvi una buona idea di cosa tenere d’occhio quando pensate di usare i design pattern:

  • Avete un team di sviluppo interno molto forte che conosce bene i design pattern.
  • State seguendo un modello SDLC che lascia spazio a discussioni approfondite sull’architettura della vostra applicazione e i design pattern sono emersi in queste discussioni.
  • La stessa serie di problemi è emersa più volte nelle discussioni di progettazione e voi conoscete il design pattern più adatto al caso.
  • Avete provato a risolvere una piccola variante del vostro problema in modo indipendente con il design pattern.
  • Grazie al design pattern, il vostro codice non sembra eccessivamente complesso.

Se un design pattern risolve il vostro problema e vi aiuta a scrivere codice semplice, riutilizzabile, modulare, con basso accoppiamento e senza “code smell”, potrebbe essere la strada giusta da percorrere.

Un altro buon consiglio da tenere a mente è evitare di ruotare tutto intorno ai design pattern. I design pattern servono per aiutarvi a risolvere i problemi. Non sono leggi da rispettare o regole da seguire rigorosamente. Le regole e le leggi fondamentali sono sempre le stesse: mantenere il codice pulito, semplice, leggibile e scalabile. Se un design pattern vi aiuta a raggiungere questi obiettivi e a risolvere il problema, allora potete andare tranquilli.

Riepilogo

I design pattern di JavaScript sono un modo meraviglioso di affrontare i problemi che molti programmatori hanno affrontato nel corso del tempo. Presentano soluzioni collaudate che si sforzano di mantenere la vostra codebase pulita e non vincolata.

Oggi sono disponibili centinaia di design pattern in grado di risolvere quasi tutti i problemi che si incontrano durante la creazione di applicazioni. Tuttavia, non tutti i design pattern risolvono sempre il vostro problema.

Proprio come qualsiasi altra convenzione di programmazione, i design pattern devono essere considerati come suggerimenti per risolvere i problemi. Non sono leggi da seguire sempre e se li trattate come tali, potreste finire per danneggiare le vostre applicazioni.

Una volta terminata la vostra app, avrete bisogno di un luogo dove ospitarla e le soluzioni di hosting di applicazioni di Kinsta sono tra le più veloci, affidabili e sicure. Dovete solo accedere al vostro account MyKinsta (il cruscotto di amministrazione personalizzato di Kinsta), collegarvi al vostro repository GitHub e lanciarlo! Inoltre vi verranno addebitate solo le risorse utilizzate dalla vostra applicazione.

Quali sono i design pattern che usate regolarmente nel vostro lavoro di programmazione software? Oppure c’è un pattern che ci è sfuggito e andrebbe messo in elenco? Fatecelo sapere nei commenti qui sotto!

Kumar Harsh

Kumar is a software developer and a technical author based in India. He specializes in JavaScript and DevOps. You can learn more about his work on his website.