在Go语言中如何有效使用组合
时间:2024-03-26
浏览:445
作者:佚名
在 Go 语言中,组合技术可避免重复代码,特别是在具有相似行为但略有不同的对象时。通过对象组合,一个对象可以包含另一个对象并委托职责。此外,接口组合允许接口包含其他接口及其方法。在本文中,描述了接口组合的用法,演示了如何将具有共同特性的两个接口合并为一个,从而避免了重复代码,并提供了具体代码示例。
问题内容
我是新手;有两个具有相似行为的文件,并被告知使用组合以避免重复代码,但不太理解组合的概念。
这两个文件具有共同的功能,但也存在差异。
player1.go
package game
type confplayer1 interface {
set(string, int) bool
move(string) bool
initialize() bool
}
func play(conf confplayer1) string {
// code for player1
}
// ... other funcs
player2.go
package game
type confPlayer2 interface {
Set(string, int) bool
Move(string) bool
// Initializer is only for Player1
}
func Play(conf confPlayer2) string {
// code for Player2, not the same as Player1.
}
// ... the same other funcs from player1.go file
// ... they differ slighly from player1.go funcs
有没有办法将所有内容合并到一个 player.go 文件中?
解决方案
golang 使用组合。
- 对象组合:使用对象组合而不是继承(继承在大多数传统语言中使用)。 对象组合意味着一个对象包含另一个对象 对象(例如对象 x)并将对象 x 的职责委托给它。 这里不是重写函数(如继承中),而是函数 调用委托给内部对象。
- 接口组合:在接口组合中,接口可以组合其他接口,并具有在接口中声明的所有方法集 内部接口成为该接口的一部分。
现在具体回答您的问题,您在这里谈论的是界面组合。您还可以在此处查看代码片段:https://play.golang.org/p/fn_mXP6XxmS
检查下面的代码:
player2.go
package game
type confplayer2 interface {
set(string, int) bool
move(string) bool
}
func play(conf confplayer2) string {
// code for player2, not the same as player1.
}
player1.go
package game
type confplayer1 interface {
confplayer2
initialize() bool
}
func play(conf confplayer1) string {
// code for player1
}
在上面的代码片段中,confplayer1接口中包含了confplayer2接口,但initialize函数只是confplayer1的一部分。
现在您可以对玩家 2 使用接口 confplayer2,对玩家 1 使用接口 confplayer1。请参阅下面的代码片段:
player.go
package game
type Player struct{
Name string
...........
...........
}
func (p Player) Set(){
.......
.......
}
func (p Player) Move(){
........
........
}
func Play(confPlayer2 player){
player.Move()
player.Set()
}文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在Go语言中如何有效使用组合》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
11.30
11.30
11.30
11.30
热门专题
