js之模板方法模式

模板方法模式的定义和组成:

模板方法模式是一种只需使用继承就可以实现的非常简单的模式。
模板方法模式由两部分结构组成,第一部分是抽象父类,第二部分是具体的实现子类。通常在抽象父类中封装了子类的算法框架,包括实现一些公共方法以及封装子类中所有方法的执行顺
序。子类通过继承这个抽象类,也继承了整个算法结构,并且可以选择重写父类的方法。

假如我们有一些平行的子类,各个子类之间有一些相同的行为,也有一些不同的行为。如果相同和不同的行为都混合在各个子类的实现中,说明这些相同的行为会在各个子类中重复出现。但实际上,相同的行为可以被搬移到另外一个单一的地方,模板方法模式就是为解决这个问题而生的。在模板方法模式中,子类实现中的相同部分被上移到父类中,而将不同的部分留待子类来实现。这也很好地体现了泛化的思想。

先泡一杯咖啡:

首先,我们先来泡一杯咖啡,如果没有什么太个性化的需求,泡咖啡的步骤通常如下:
(1) 把水煮沸
(2) 用沸水冲泡咖啡
(3) 把咖啡倒进杯子
(4) 加糖和牛奶
通过下面这段代码,我们就能得到一杯香浓的咖啡:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        var Coffee = function(){};
        Coffee.prototype.boilWater = function(){
            console.log( '把水煮沸' );
        };
        Coffee.prototype.brewCoffeeGriends = function(){
            console.log( '用沸水冲泡咖啡' );
        };
        Coffee.prototype.pourInCup = function(){
            console.log( '把咖啡倒进杯子' );
        };
        Coffee.prototype.addSugarAndMilk = function(){
            console.log( '加糖和牛奶' );
        };
        Coffee.prototype.init = function(){
            this.boilWater();
            this.brewCoffeeGriends();
            this.pourInCup();
            this.addSugarAndMilk();
        };
        var coffee = new Coffee();
        coffee.init();
    </script>
</body>
</html>

泡一壶茶:

接下来,开始准备我们的茶,泡茶的步骤跟泡咖啡的步骤相差并不大:
(1) 把水煮沸
(2) 用沸水浸泡茶叶
(3) 把茶水倒进杯子
(4) 加柠檬
同样用一段代码来实现泡茶的步骤:

var Tea = function(){};
Tea.prototype.boilWater = function(){
    console.log( '把水煮沸' );
};
Tea.prototype.steepTeaBag = function(){
    console.log( '用沸水浸泡茶叶' );
};
Tea.prototype.pourInCup = function(){
    console.log( '把茶水倒进杯子' );
};
Tea.prototype.addLemon = function(){
    console.log( '加柠檬' );
};
Tea.prototype.init = function(){
    this.boilWater();
    this.steepTeaBag();
    this.pourInCup();
    this.addLemon();
};
var tea = new Tea();
tea.init();

分离出共同点:

var Beverage = function(){};
Beverage.prototype.boilWater = function(){
console.log( '把水煮沸' );
};
Beverage.prototype.brew = function(){
    throw new Error( '子类必须重写 brew 方法' );
    }; // 空方法,应该由子类重写
Beverage.prototype.pourInCup = function(){
    throw new Error( '子类必须重写 pourInCup  方法' );
    }; // 空方法,应该由子类重写
Beverage.prototype.addCondiments = function(){
    throw new Error( '子类必须重写 addCondiments 方法' );
    }; // 空方法,应该由子类重写
Beverage.prototype.init = function(){
    this.boilWater();
    this.brew();
    this.pourInCup();
    this.addCondiments();
};

创建 Coffee 子类和 Tea 子类:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        var Beverage = function(){};
        Beverage.prototype.boilWater = function(){
            console.log( '把水煮沸' );
        };
        Beverage.prototype.brew = function(){}; // 空方法,应该由子类重写
        Beverage.prototype.pourInCup = function(){}; // 空方法,应该由子类重写
        Beverage.prototype.addCondiments = function(){}; // 空方法,应该由子类重写
        Beverage.prototype.init = function(){
            this.boilWater();
            this.brew();
            this.pourInCup();
            this.addCondiments();
        };

        var Coffee = function(){};
        Coffee.prototype = new Beverage();
        Coffee.prototype.brew = function(){
            console.log( '用沸水冲泡咖啡' );
        };
        Coffee.prototype.pourInCup = function(){
            console.log( '把咖啡倒进杯子' );
        };
        Coffee.prototype.addCondiments = function(){
            console.log( '加糖和牛奶' );
        };
        var Coffee = new Coffee();
        Coffee.init();
    </script>
</body>
</html>

本章一直讨论的是模板方法模式,那么在上面的例子中,到底谁才是所谓的模板方法呢?答案是 Beverage.prototype.init 。

Beverage.prototype.init 被称为模板方法的原因是,该方法中封装了子类的算法框架,它作为一个算法的模板,指导子类以何种顺序去执行哪些方法。在 Beverage.prototype.init 方法中,
算法内的每一个步骤都清楚地展示在我们眼前。

模板方法模式的使用场景:

在 Web开发中也能找到很多模板方法模式的适用场景,比如我们在构建一系列的 UI组件,
这些组件的构建过程一般如下所示:
(1) 初始化一个 div容器;
(2) 通过 ajax请求拉取相应的数据;
(3) 把数据渲染到 div容器里面,完成组件的构造;
(4) 通知用户组件渲染完毕。

我们看到,任何组件的构建都遵循上面的 4 步,其中第(1)步和第(4)步是相同的。第(2)步不同的地方只是请求 ajax的远程地址,第(3)步不同的地方是渲染数据的方式。

于是我们可以把这 4个步骤都抽象到父类的模板方法里面,父类中还可以顺便提供第(1)步和第(4)步的具体实现。当子类继承这个父类之后,会重写模板方法里面的第(2)步和第(3)步。

添加钩子

通过模板方法模式,我们在父类中封装了子类的算法框架。这些算法框架在正常状态下是适用于大多数子类的,但如果有一些特别“个性”的子类呢?比如我们在饮料类 Beverage 中封装了
饮料的冲泡顺序:
(1) 把水煮沸
(2) 用沸水冲泡饮料
(3) 把饮料倒进杯子
(4) 加调料
这 4个冲泡饮料的步骤适用于咖啡和茶,在我们的饮料店里,根据这 4个步骤制作出来的咖啡和茶,一直顺利地提供给绝大部分客人享用。但有一些客人喝咖啡是不加调料(糖和牛奶)的。既然 Beverage 作为父类,已经规定好了冲泡饮料的 4个步骤,那么有什么办法可以让子类不受这个约束呢?

钩子方法( hook )可以用来解决这个问题,放置钩子是隔离变化的一种常见手段。我们在父类中容易变化的地方放置钩子,钩子可以有一个默认的实现,究竟要不要“挂钩”,这由子类自行决定。钩子方法的返回结果决定了模板方法后面部分的执行步骤,也就是程序接下来的走向,这样一来,程序就拥有了变化的可能。在这个例子里,我们把挂钩的名字定为customerWantsCondiments ,接下来将挂钩放入 Beverage
类,看看我们如何得到一杯不需要糖和牛奶的咖啡,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        var Beverage = function(){};
        Beverage.prototype.boilWater = function(){
            console.log( '把水煮沸' );
        };
        Beverage.prototype.brew = function(){
            throw new Error( '子类必须重写 brew 方法' );
        };
        Beverage.prototype.pourInCup = function(){
            throw new Error( '子类必须重写 pourInCup 方法' );
        };
        Beverage.prototype.addCondiments = function(){
            throw new Error( '子类必须重写 addCondiments 方法' );
        };
        Beverage.prototype.customerWantsCondiments = function(){
            return true; // 默认需要调料
        };
        Beverage.prototype.init = function(){
            this.boilWater();
            this.brew();
            this.pourInCup();
            if ( this.customerWantsCondiments() ){ // 如果挂钩返回 true,则需要调料
                this.addCondiments();
            }
        };
        var CoffeeWithHook = function(){};
        CoffeeWithHook.prototype = new Beverage();
        CoffeeWithHook.prototype.brew = function(){
            console.log( '用沸水冲泡咖啡' );
        };
        CoffeeWithHook.prototype.pourInCup = function(){
            console.log( '把咖啡倒进杯子' );
        };
        CoffeeWithHook.prototype.addCondiments = function(){
            console.log( '加糖和牛奶' );
        };
        CoffeeWithHook.prototype.customerWantsCondiments = function(){
            return window.confirm( '请问需要调料吗?' );
        };
        var coffeeWithHook = new CoffeeWithHook();
        coffeeWithHook.init();
    </script>
</body>
</html>

真的需要“继承”吗?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        var Beverage = function( param ){
            var boilWater = function(){
                console.log( '把水煮沸' );
            };
            var brew = param.brew || function(){
                    throw new Error( '必须传递 brew 方法' );
                };
            var pourInCup = param.pourInCup || function(){
                    throw new Error( '必须传递 pourInCup 方法' );
                };
            var addCondiments = param.addCondiments || function(){
                    throw new Error( '必须传递 addCondiments 方法' );
                };
            var F = function(){};
            F.prototype.init = function(){
                boilWater();
                brew();
                pourInCup();
                addCondiments();
            };
            return F;
        };
        var Coffee = Beverage({
            brew: function(){
                console.log( '用沸水冲泡咖啡' );
            },
            pourInCup: function(){
                console.log( '把咖啡倒进杯子' );
            },
            addCondiments: function(){
                console.log( '加糖和牛奶' );
            }
        });
        var Tea = Beverage({
            brew: function(){
                console.log( '用沸水浸泡茶叶' );
            },
            pourInCup: function(){
                console.log( '把茶倒进杯子' );
            },
            addCondiments: function(){
                console.log( '加柠檬' );
            }
        });
        var coffee = new Coffee();
        coffee.init();
        var tea = new Tea();
        tea.init();
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值