Golang怎么实现组合模式和装饰模式


今天主机评测网小编给大家分享一下Golang怎么实现组合模式和装饰模式的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

组合模式

组合是一种结构设计模式,它允许将对象组合成树状结构,并将其作为单一对象使用。对于需要构建树形结构的大多数问题,组合结构成为常用的解决方案,它最大特性是能够在整个树结构上递归运行方法并对结果进行汇总。

这里通过操作系统的文件系统来理posite模式。在文件系统中有两种类型的对象: 文件和文件夹。有些情况下文件和文件夹应该以相同的方式对待。这就posite模式派上用场的地方。

假设您需要在文件系统中对特定的关键字进行搜索。此搜索操作同时适用于文件和文件夹。对于一个文件,它只会查看文件的内容;对于一个文件夹,它将遍历该文件夹的所有文件以找到该关键字。下面通过实例进行说明。

<h4ponent.go

定义节点类型:

packagemaintype&nbspponentinterface{search(string)}

file.go

定义文件类型节点,实现search方法:

packagemainimport"fmt"typeFilestruct{namestring}func(f*File)search(keywordstring){fmt.Printf("Searchingforkeyword%sinfile%s\n",keyword,f.name)}func(f*File)getName()string{returnf.name}

folder.go

定义文件夹类型节点,也实现search方法:

packagemainimport"fmt"typeFolderstruct{&nbspponents[ponentnamestring}func(f*Folder)search(keywordstring){fmt.Printf("Serchingrecursivelyforkeyword%sinfolder%s\n",keyword,f.name)for_,&nbspposite:=rangefponents{&nbspposite.search(keyword)}}func(f*Folder)add(c&nbspponent){fponents=append(fponents,c)}

组合测试

定义main.go文件进行组合测试:

packagemainfuncmain(){file1:=&File{name:"File1"}file2:=&File{name:"File2"}file3:=&File{name:"File3"}folder1:=&Folder{name:"Folder1",}folder1.add(file1)folder2:=&Folder{name:"Folder2",}folder2.add(file2)folder2.add(file3)folder2.add(folder1)folder2.search("rose")}

输出结果:

Serching recursively for keyword rose in folder Folder2
Searching for keyword rose in file File2
Searching for keyword rose in file File3
Serching recursively for keyword rose in folder Folder1
Searching for keyword rose in file File1

装饰模式

装饰模式也是一种结构模式,通过将对象放置在称为装饰器的特殊包装对象中,允许动态地向对象添加新行为。使用装饰器可以无数次包装对象,因为目标对象和装饰器遵循相同的接口。结果对象将获得所有包装器的堆叠行为。下面通过实例进行说明:

pizza.go

定义披萨类型,包括getPrice方法:

packagemaintypeIPizzainterface{getPrice()int}

veggieMania.go

定义素食披萨,并实现getPrice方法:

packagemaintypeVeggeManiastruct{}func(p*VeggeMania)getPrice()int{return15}

tomatoTopping.go

定义番茄匹萨,再次对getPrice方法进行装饰:

packagemaintypeTomatoToppingstruct{pizzaIPizza}func(c*TomatoTopping)getPrice()int{pizzaPrice:=c.pizza.getPrice()returnpizzaPrice+7}

cheeseTopping.go

定义奶酪匹萨,同时再次对getPrice方法进行装饰:

packagemaintypeCheeseToppingstruct{pizzaIPizza}func(c*CheeseTopping)getPrice()int{pizzaPrice:=c.pizza.getPrice()returnpizzaPrice+10}

main.go

下面定义具体实现,展示装饰模式的应用:

packagemainimport"fmt"funcmain(){//定义匹萨pizza:=&VeggeMania{}//增加奶酪pizzaWithCheese:=&CheeseTopping{pizza:pizza,}//增加番茄pizzaWithCheeseAndTomato:=&TomatoTopping{pizza:pizzaWithCheese,}fmt.Printf("PriceofveggeManiawithtomatoandcheesetoppingis%d\n",pizzaWithCheeseAndTomato.getPrice())}

输出结果:

Price of veggeMania with tomato and cheese topping is 32

以上就是“Golang怎么实现组合模式和装饰模式”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注主机评测网行业资讯频道。


上一篇:Typescript中interface与type的相同点与不同点是什么

下一篇:go语言支持哪些函数


Copyright © 2002-2019 测速网 https://www.inhv.cn/ 皖ICP备2023010105号 城市 地区 街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!
热门搜索