- Published on
Three Design Patterns should to know with Javascript
- Authors
- Name
- Panuwat Boonrod
- @nilpanuwat
Overview
In this article, I will introduce four design patterns that should to know with Javascript. I will also show how to use these design patterns with Javascript.
Four design patterns that should to know with Javascript
How to use these design patterns with Javascript
Singleton Pattern
Example
singleton-pattern-1.jsx
class Singleton {
static instance
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton()
}
return Singleton.instance
}
}
When to use Singleton Pattern ?
singleton-pattern-2.jsx
const instance1 = Singleton.getInstance()
const instance2 = Singleton.getInstance()
console.log(instance1 === instance2)
// true
Pros:
- Easy to use
- Reusability
- Easy to debug
Cons:
- Hard to test
Factory Pattern
Example
factory-pattern-1.jsx
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
static createPerson(name, age) {
return new Person(name, age)
}
}
When to use Factory Pattern ?
factory-pattern-2.jsx
const person1 = Person.createPerson('John', 30)
const person2 = Person.createPerson('Jane', 25)
console.log(person1)
// { name: 'John', age: 30 }
console.log(person2)
// { name: 'Jane', age: 25 }
Pros:
- Encapsulates object creation logic.
- Supports easy object extension.
Cons:
- Overhead for simple objects.
Decorator Pattern
Example
decorator-pattern-1.jsx
class Car {
getCar() {
return {
name: 'Car'
}
}
getModCar() {
return {
...this.getCar(),
color: 'red'
}
}
getModCar2() {
return {
...this.getCar(),
color: 'yellow'
}
}
}
When to use Decorator Pattern ?
decorator-pattern-2.jsx
const car = new Car()
console.log(car.getCar())
// { name: 'Car' }
console.log(car.getModCar())
// { name: 'Car', color: 'red' }
console.log(car.getModCar2())
// { name: 'Car', color: 'yellow' }
Pros:
- Extends functionality dynamically.
Cons:
- Can make the code harder to read if overused.
Conclusion
As you can see, these patterns are useful for Readability, Cleanness, Reusability, and Modularity, That's very helpful for team.
The next chapter will introduce more patterns e.g Stategy, Observer, etc.