阅读《JavaScript设计模式》第三章心得

简单工厂模式

1、通过类实例化对象创建

传统的用面向对象方法去创建很多类去实现某些功能不妥当,这样不仅占用的很多类名称,而且别人使用这些方法的同时要记住每个类的名字,所以这样不适合团队开发,所以我们可以把这些类封装到一个函数里面,这样别人用你的类就不用记住每个类的名字,只用记住工厂的名字就可以了。直接上代码:

 1         //篮球基类
 2         var Basketball = function(){
 3             this.intro = '篮球盛行于美国';
 4         }
 5         Basketball.prototype = {
 6             getMember:function(){
 7                 console.log('每个队伍需要5名队员');
 8             },
 9             getBallSize : function(){
10                 console.log('篮球很大')
11             }
12         }
13         //足球基类
14         var Football = function(){
15             this.intro='足球在世界范围内很流行';
16         }
17         Football.prototype ={
18             getMember:function(){
19                 console.log('每个队伍需要11名队员');
20             },
21             getBallSize:function(){
22                 console.log('足球很大');
23             }
24         }
25         //网球基类
26         var Tennis = function(){
27             this.intro = '每年有很多网球比赛'
28         }
29         Tennis.prototype ={
30             getMenber:function(){
31                 console.log('每个队伍至少需要一名队员')
32             },
33             getBallSize:function(){
34                 console.log('网球很小')
35             }
36         }
37         //运动工厂
38         var SportsFactory = function(name){
39             switch (name){
40                 case 'NBA':
41                     return new Basketball();
42                 case 'wordCup':
43                     return new Football();
44                 case 'FrenchOpen':
45                     return new Tennis();
46             }
47         }
48         //为世界杯创建一个足球,只需要记住运动工厂SportsFactory,调用并创建
49         var footnall = SportsFactory("wordCup");
50         console.log(footnall);
51         console.log(footnall.intro);
52         footnall.getMember();

2、通过创建一个新的对象然后包装增强其属性和功能来实现。

 这样实现的好处是可以不用创建很多类名。有些相同的功能可以复用。代码如下:

 1 function createPop(type, text) {
 2             var o = new Object();
 3             o.content = text;
 4             o.show = function() {
 5                 //显示方法
 6             };
 7             if(type == 'alert') {
 8                 //警告框差异部分
 9             }
10             if(type == 'prompt') {
11                 //提示框差异部分
12             }
13             if(type = 'confirm') {
14                 //确认框差异部分
15             }
16             //将对象返回
17             return o;
18         }
19         //创建警示框
20         var userNameAlert = createPop('alert', '用户名只能是26个字母或者数字');

猜你喜欢

转载自www.cnblogs.com/Juaoie/p/9195199.html