码迷,mamicode.com
首页 > 其他好文 > 详细

模板方法模式

时间:2015-07-08 09:28:01      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

   模板方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。——《HEAD FIRST 设计模式》

   我的golang代码:

 1 package template
 2 
 3 import (
 4     "fmt"
 5 )
 6 
 7 type Caffeine interface {
 8     brew()
 9     addCondiments()
10 }
11 
12 ///////////////////////////////////////////////
13 type Tea struct {
14 }
15 
16 func (t *Tea) brew() {
17     fmt.Println("tea brew!")
18 }
19 
20 func (t *Tea) addCondiments() {
21     fmt.Println("tea addCondiments!")
22 }
23 
24 //////////////////////////////////////////////
25 type Coffee struct {
26 }
27 
28 func (t *Coffee) brew() {
29     fmt.Println("coffee brew!")
30 }
31 
32 func (t *Coffee) addCondiments() {
33     fmt.Println("coffee addCondiments!")
34 }
35 
36 //////////////////////////////////////////////
37 type CaffeineBeverage struct {
38     Caffeine
39 }
40 
41 func NewCaffeineBeverage(c Caffeine) *CaffeineBeverage {
42     t := new(CaffeineBeverage)
43     t.Caffeine = c
44     return t
45 }
46 
47 func (t *CaffeineBeverage) PrepareRecipe() {
48     t.boilWater()
49     t.brew()
50     t.pourInCup()
51     t.addCondiments()
52 }
53 
54 func (t *CaffeineBeverage) boilWater() {
55     fmt.Println("boilWater!")
56 }
57 
58 func (t *CaffeineBeverage) pourInCup() {
59     fmt.Println("pourInCup!")
60 }

   个人感悟:待留。

模板方法模式

标签:

原文地址:http://www.cnblogs.com/foolbread/p/4629167.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!