Creating objects in JS is customary with the new keyword and class constructors (which can also be used for object literals).
A factory pattern is a pattern that helps eliminate two of class dependencies.
The factory model is divided into simple Factory mode and complex Factory mode, which is mainly about simple Factory mode.
Simple Factory mode: Use a class to generate an instance.
Complex Factory mode: Use subclasses to determine which instance of a particular class A member variable should be.
Simple Factory mode:
Common object methods Create and Invoke
varBallshop =function(){}; Ballshop.prototype={sellball:function(model) {varBall ; Switch(model) { Case"Tennis": Ball=NewTennisball (); Break; Case"Bask": Ball=NewBasketBall (); Break; Case"Volly": Ball=NewVollyball (); Break; default: Ball=NewFootBall (); Break; } returnBall ; }} varBalltype =Newballshop (); Balltype. Sellball ("Tennis");
The above method can be used in most cases, but the extensibility is not friendly, if you need to add some new ball, you must modify the switch part of the ball.
Put this part alone and give it to a simple factory object:
<script type= "Text/javascript" >varBasketball=function() {Console.log ("BASEketball is hotting at UnitedStates"); } varTennisball=function() {Console.log ("You should buy a Tennisball") } varVollyball=function() {Console.log ("Vollyball is very interesting"); } varFootball=function() {Console.log ("FootBall ...") }
varballfactory={createball:function(model) {varBall ; Switch(model) { Case"Tennis": Ball=NewTennisball (); Break; Case"Bask": Ball=NewBasketBall (); Break; Case"Volly": Ball=NewVollyball (); Break; default: Ball=NewFootBall (); Break; } returnBall ; } } varBallshop =function(){}; Ballshop.prototype={sellball:function(model) {varBall =Ballfactory.createball (model); returnBall ; } } //called varball1=NewBallshop (); Ball1.sellball ("Tennis"); varBall2=Newballshop () Ball2.sellball ("Balls"); </script>
Ballfactory is a monomer separated from the ballshop. Can reduce the coupling degree. When you need to add a new type, just modify the Ballfactory factory monomer object.
The result of the last run is:
Use JavaScript to complete a simple factory design pattern.