Series catalog:
- [1] — Creative design Patterns
- JavaScript Design Pattern Parsing [2] — Structural design Pattern
- JavaScript Design Pattern Parsing [3] — Behavioral design Patterns
- JavaScript Design Pattern parsing [4] — Decorator pattern, appearance pattern, mediator pattern
The factory pattern
The factory pattern is a design pattern used to create objects.
It does not expose the concrete logic that creates the object, but encapsulates the logic in a function called a factory, divided into simple factories and factory methods depending on the level of abstraction
Simple Factory model
The power to create an object class from a factory. Mainly used to create objects of the same class.
// Class Pet {// constructor() {this. Species = props. Species; this.sound = props.sound; } // Static getProps(pet) {switch (pet) {case 'dog':
return new Pet({species: 'dog', sound: 'woof'});
case 'cat':
return new Pet({species: 'cat', sound: 'meow'});
case 'bird':
return new Pet({species: 'bird', sound: 'chirping'}); }}}let Adog = Pet.getProps('dog');
console.log(Adog.sound); // woof
let Acat = Pet.getProps('cat');
console.log(Acat.sound); // meow
let Abird = Pet.getProps('bird');
console.log(Abird.sound); // chirping
Copy the code
Simple factories let us pass a single parameter to the factory function to get the corresponding instance object without knowing the details, but the simple factory pattern can only be used when the number of objects is small and the object creation logic is not complex.
Factory method pattern
The factory method pattern lets us defer instance creation to subclasses, so that our core class becomes abstract, and encapsulates the new operation by separating the constructor from the creator.
// Factory method pattern class Pet {constructor(species =' ', sound = ' ') { this.species = species; this.sound = sound; }} class constructor extends Pet {constructor(sound) {super(species, sound); } create(pet) { switch (pet) {case 'dog':
return new PetShop('dog'.'woof');
case 'cat':
return new PetShop('cat'.'meow');
case 'bird':
return new PetShop('bird'.'chirping'); }}}letthePetShop = new PetShop(); // Create the instance through the creator's methodlet shopDog = thePetShop.create('dog');
console.log(shopDog.sound); // woof
let shopCat = thePetShop.create('cat');
console.log(shopCat.sound); // meow
let shopBird = thePetShop.create('bird');
console.log(shopBird.sound); // chirping
Copy the code
We can think of a factory method as a factory for instantiating objects, which does only one thing: instantiating objects.
conclusion
- The factory pattern separates the constructor from the creator
- In line with the principle of openness and closure
The singleton pattern
The core idea of the singleton pattern is to ensure that a class has only one instance and provide a global access point to access it
The singleton pattern of JavaScript is different from object-oriented applications and has many uses in real development, such as improving page performance and avoiding unnecessary DOM manipulation. For example, the login float window that appears after we click the login button will only be created once, no matter how many times we click the login button. This can be created using the lazy singleton pattern.
Lazy singletons are instances of objects that are created when values are needed.
<html>
<head>
<meta charset="UTF-8">
<title>Single Pattern</title>
</head>
<body>
<button id="btn">Let me login</button>
<script>
class Login {
createLayout() {
console.log('invoked')
let theDiv = document.createElement('div');
theDiv.innerHTML = 'I'm a floating window.'
document.body.appendChild(theDiv)
theDiv.style.display = 'none'
return theDiv
}
}
class Single {
getSingle(fn) {
let result;
return function () {
return result || (result = fn.apply(this.arguments))}}}let theBtn = document.getElementById('btn')
let single = new Single()
let login = new Login()
// Due to the closure, createLoginLayer refers to result, so when single.getSingle is done, result is not destroyed in memory
// The createLoginLayer function already has result in its scope chain, so return result directly
let createLoginLayer = single.getSingle(login.createLayout)
theBtn.onclick= function() {
let layout = createLoginLayer()
layout.style.display = 'block'
}
</script>
</body>
</html>
Copy the code
At this point we can click the log on button successively, but the invoked example is printed only once, indicating that the instance was created once and the example used thereafter is unique.
conclusion
- The main idea of the singleton pattern is that if an instance is created, it is returned directly, and if it is not, a new instance is created.
- In line with the principle of openness and closure.
The prototype pattern
The prototype instance specifies the type of object to create, and the new object is created by copying the prototype.
In JavaScript, the way to implement the prototype pattern is the object.create method, which provides the _proto_ of the newly created Object by using an existing Object.
- Every function data type (ordinary function, class) has a built-in attribute:
prototype
And the property is the value of an object data type. - And on Prototype the browser added a constructor naturally
constructor
, the property value is the current function (class) itself. - Each object data type leaf has an inherent property
proto
, the property value is the stereotype of the class to which the current instance belongs.
var prototype = {
name: 'Reaper'.getName: function() {
return this.name; }}// Also note that object. create is a shallow copy
var obj = Object.create(prototype,
{
skill: {value: 'FE'}})console.log(obj.getName()); //Reaper
console.log(obj.skill); // FE
console.log(obj.__proto__ === prototype); //true
Copy the code
Prototype several methods
1. Object. The create () method
let proto = {a:1}
let propertiesObject = {
b: {
value: 2
}
}
let obj = Object.create(proto, propertiesObject)
console.log(obj.__proto__ === proto); // true
Copy the code
2. Method inheritance
// Method inheritancelet proto = function() {}
proto.prototype.excute = function() {}
let child = functionPrototype = new proto();Copy the code
3. Default inheritance of functions from Object
let Foo = function() {}
console.log(Foo.prototype.__proto__ === Object.prototype); // true
Copy the code
4.isPrototypeOf
prototypeObj.isPrototypeOf(obj)
Copy the code
5.instanceof
Contructor. Prototype appears on obJ’s prototype chain
obj instanceof contructor
Copy the code
6.getPrototypeOf
The object.getProtoTypeof (obj) method returns the Prototype of the specified Object obj (internal [[Prototype]] property value).
Object.getPrototypeOf(obj)
Copy the code
7.setPrototypeOf
Sets the Prototype of a specified object (that is, the internal [[Prototype]] property) to another object or null
var obj = {}
var prototypeObj = {}
Object.setPrototypeOf(obj, prototypeObj)
console.log(obj.__proto__ === prototypeObj) // true
Copy the code
Repository source: javascript-Design Patterns