Code Patterns
Creational patterns deal with object creation
mechanisms, providing a way to create objects that
are flexible, reusable, and less dependent on specific
implementations. These patterns aim to abstract the
instantiation process, making the system independent
of the concrete classes used.
Here are some Creational Patterns listed below:
Singleton
Factory Method
Builder
Structural patterns deal with the composition of
objects and classes, ensuring that they work together
efficiently. These patterns focus on simplifying
relationships between entities and promoting flexibility
in the structure.
Here are some Structural Patterns listed below:
Adapter
Composite
Ensures that a class has only one instance and
provides a global point of access to it.
class Singleton {
constructor() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
Defines an interface for creating objects but lets
subclasses decide the type of object to create.
class ShapeFactory {
static createShape(type) {
if (type === 'circle') return new Circle();
if (type === 'square') return new Square();
}
}
const shape = ShapeFactory.createShape('circle');
Separates the construction of a complex object from its representation.
class Burger {
constructor() {
this.ingredients = [];
}
addIngredient(ingredient) {
this.ingredients.push(ingredient);
return this;
}
}
const burger = new Burger().addIngredient('patty').addIngredient('lettuce');
Converts an interface into another interface that a client expects.
class OldAPI {
oldMethod() { return 'old method'; }
}
class Adapter {
constructor() { this.oldApi = new OldAPI(); }
newMethod() { return this.oldApi.oldMethod(); }
}
const adapted = new Adapter();
console.log(adapted.newMethod()); // 'old method'Adds behavior to objects dynamically.
class Coffee {
cost() { return 5; }
}
class MilkDecorator {
constructor(coffee) { this.coffee = coffee; }
cost() { return this.coffee.cost() + 1; }
}
const coffeeWithMilk = new MilkDecorator(new Coffee());
console.log(coffeeWithMilk.cost()); // 6