Go设计模式-模版方法模式

模版方法模式

文章目录


模版方法模式意在定义一个操作中的算法框架,将公共的操作抽象出来放在抽象接口中定义出一套抽象框架,而不同的操作实现则延迟到子类去实现

例如做饭这一个操作中可能有多个子操作:

  • 开煤气
  • 开火
  • 做饭
  • 关火
  • 关煤气

其中除了做饭不同其他都是相同的,那么相同的就可以放在抽象类中实现,不同的则延迟到子类实现

代码目录结构:

.
├── Impl
│   └── KevinCookie.go
├── abstractImpl
│   └── abstrateCookie.go
├── docookie_test.go
└── mytemplate
    └── cookieTemplate.go

操作框架抽象到接口中

// DoCookie 做饭操作模版
package mytemplate

// DoCookie 做饭操作模版
type DoCookie interface {
	Open()
	Fire()
	Cookie()
	CloseFire()
	Close()
}

抽象实现:实现了公共的一样的操作

package abstractImpl

import "fmt"

// AbstrateCookie 抽象做饭类
type AbstrateCookie struct {

}

// open 开煤气
func (c *AbstrateCookie) Open()  {
	fmt.Print("开煤气")
}

// fire 点火
func (c *AbstrateCookie) Fire()  {
	fmt.Print("开煤气")
}

// 做饭
func (c *AbstrateCookie) Cookie()  {
	fmt.Print("开煤气")
}

// closeFire 关火
func (c *AbstrateCookie) CloseFire()  {
	fmt.Print("开煤气")
}

// 关煤气
func (c *AbstrateCookie) Close()  {
	fmt.Print("开煤气")
}

不同操作的具体实现交给抽象类的子类实现:

package Impl

import (
	"awesomeProject3/abstractMethod/abstractImpl"
	"fmt"
)

// KevinCookie kevin做饭
type KevinCookie struct {
	abstractImpl.AbstrateCookie	
}

func (c *KevinCookie) Cookie()  {
	fmt.Print("Kevin今日做饭,做的是西红柿炒鸡蛋")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值