JavaScript design patterns Classic factory patterns

  • 2021-01-02 21:45:40
  • OfStack

1. Concept of factory mode

The factory pattern defines an interface for creating objects, which subclasses decide which class to instantiate. This pattern delays the instantiation of a class to a subclass. Subclasses, on the other hand, can override interface methods to specify their own object types (abstract factories) when they are created.

This pattern is useful for 10 points, especially when the process of creating an object is assigned, such as depending on many Settings files, etc. Also, you'll often see factory methods in programs that let subclasses define the type of object that needs to be created.

2. Role of factory mode and matters needing attention

Role of model:

1. Object construction is 10 points complicated -- it is easy to wear shoes, but the process of making shoes is 10 points complicated

2. Different instances should be created depending on the specific environment -- the factory can make shoes and clothes, and the factory can make shoes I need (different shoes), and then send them to the designated place (different places), which can be interpreted as different instances

3. Deal with a large number of small objects with the same attributes -- for example, buy a pair of shoes, there is no need to go to a factory for production

Notes:

1. Don't abuse factories, sometimes just to add complexity to code -- 3 above

3. Code of factory mode and practical summary


<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
//1. The factory should have a director to decide which product line to run 
//2. consumers - "Subclass 
var gongchang = {};
gongchang.chanyifu = function(){
this.gongren = 50;
alert(" We have a "+this.gongren);
}
gongchang.chanxie = function(){
this.gongren = 100;
alert(" Production of shoes ");
}
gongchang.yunshu = function(){
this.gongren = 10;
alert(" transport ");
}
gongchang.changzhang = function(para){
return new gongchang[para]();
}
var me = gongchang.changzhang("chanxie");
alert(me.gongren);
</script>
</body>
</html>

The above is the classic factory mode of JavaScript design mode introduced by this site, I hope it will be helpful to you!


Related articles: