创建文件Downloader.go
package template
import "fmt"
type Downloader interface {
Download(url string)
}
type template struct {
implement
url string
}
type implement interface {
download()
save()
}
func NewTemplate(impl implement) *template {
return &template{impl, ""}
}
func (t *template) Download(url string) {
fmt.Println("模板下载start")
t.url = url
t.implement.download()
t.implement.save()
fmt.Println("模板下载end")
}
func (t *template) save() {
fmt.Println("模板下载保存")
t.implement.save()
}
创建文件HttpDown.go
package template
import "fmt"
type HttpDownload struct {
*template
}
func NewHttpDownload() Downloader {
downloader := &HttpDownload{}
template := NewTemplate(downloader)
downloader.template = template
return downloader
}
func (hd *HttpDownload) download() {
fmt.Printf("http down %s \n", hd.url)
}
func (hd *HttpDownload) save() {
fmt.Printf("http save \n")
}
创建文件FtpDown.go
package template
import "fmt"
type FtpDownload struct {
*template
}
func NewFtpDownload() Downloader {
downloader := &FtpDownload{}
template := NewTemplate(downloader)
downloader.template = template
return downloader
}
func (fd *FtpDownload) download() {
fmt.Printf("ftp down %s \n", fd.url)
}
func (fd *FtpDownload) save() {
fmt.Printf("ftp save \n")
}
main.go
package main
import "ssp_api_go/test/design/template"
func main() {
var downloader template.Downloader = template.NewHttpDownload()
downloader.Download("https://ijackey.com")
var downloader2 template.Downloader = template.NewFtpDownload()
downloader2.Download("https://ijackey.com")
}