Simple Factory mode
1. Object creation through class instantiation
The traditional use of object-oriented methods to create a lot of classes to implement some function is not appropriate, so not only occupy a lot of class names, and others use these methods to remember the name of each class, so it is not suitable for team development, so we can encapsulate these classes into a function, So that others use your class will not have to remember the name of each class, just remember the name of the factory. Directly on the code:
1 //Basketball base class2 varBasketball =function(){3 This. Intro = ' Basketball Prevails in America ';4 }5Basketball.prototype = {6GetMember:function(){7Console.log (' Each team needs 5 players ');8 },9Getballsize:function(){TenConsole.log (' Basketball is big ')) One } A } - //Football base class - varFootball =function(){ the This. intro= ' Football is very popular around the world '; - } -Football.prototype ={ -GetMember:function(){ +Console.log (' Each team needs 11 players '); - }, +Getballsize:function(){ AConsole.log (' Football is big ')); at } - } - //Tennis base class - varTennis =function(){ - This. Intro = ' There are a lot of tennis competitions every year ' - } inTennis.prototype ={ -Getmenber:function(){ toConsole.log (' Each team needs at least one player ')) + }, -Getballsize:function(){ theConsole.log (' Tennis is very small ')) * } $ }Panax Notoginseng //Sports Factory - varSportsfactory =function(name) { the Switch(name) { + Case' NBA ': A return NewBasketball (); the Case' Wordcup ': + return NewFootball (); - Case' Frenchopen ': $ return Newtennis (); $ } - } - //To create a football for the World Cup, just remember the sports factory sportsfactory, call and create the varFootnall = Sportsfactory ("Wordcup"); - Console.log (footnall);Wuyi Console.log (Footnall.intro); theFootnall.getmember ();
2. It is implemented by creating a new object and then wrapping it to enhance its properties and functionality.
The benefit of this implementation is that there is no need to create many class names. Some of the same features can be reused. The code is as follows:
1 functionCreatepop (type, text) {2 varo =NewObject ();3O.content =text;4O.show =function() {5 //Display Method6 };7 if(Type = = ' Alert ') {8 //Warning Box Difference Section9 }Ten if(Type = = ' Prompt ')) { One //Hint Box difference section A } - if(type = ' confirm ')) { - //Confirmation Box Difference Section the } - //returns an object - returno; - } + //Create alert Box - varUsernamealert = Createpop (' alert ', ' username can only be 26 letters or numbers ');
Read the third chapter of JavaScript design Patterns