Home >Web Front-end >JS Tutorial >JavaScript design pattern classic factory pattern_javascript skills
1. Factory model concept
The factory pattern defines an interface for creating objects. This interface determines which class to instantiate by the subclass. This pattern defers instantiation of a class to subclasses. Subclasses can override interface methods to specify their own object types (abstract factory) when creating.
This mode is very useful, especially when assigning values to the process of creating objects, such as relying on many settings files. Moreover, you will often see factory methods in programs, which are used to let subclasses define the types of objects that need to be created.
2. The role and precautions of factory mode
Mode function:
1. Object construction is very complex - it is very simple for us to put on shoes, but the process of making shoes is very complicated
2. Different instances need to be created depending on the specific environment - the factory can make shoes and clothes, and the factory can make the shoes I need (the shoes are different) and then send them to the designated place (the place can be different), which is understandable for different instances
3. Handle a large number of small objects with the same attributes - such as buying a pair of shoes, there is no need to find a factory to produce them
Note:
1. Don’t abuse the factory. Sometimes it just adds complexity to the code - as shown in 3 above
3. Factory pattern code and practical summary
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <script> //1.工厂应该有厂长来决定运行到底哪条产品线 //2.消费者-》子类 var gongchang = {}; gongchang.chanyifu = function(){ this.gongren = 50; alert("我们有"+this.gongren); } gongchang.chanxie = function(){ this.gongren = 100; alert("产鞋子"); } gongchang.yunshu = function(){ this.gongren = 10; alert("运输"); } gongchang.changzhang = function(para){ return new gongchang[para](); } var me = gongchang.changzhang("chanxie"); alert(me.gongren); </script> </body> </html>
The above is the classic JavaScript design pattern factory pattern introduced by the editor to you. I hope it will be helpful to you!