Go中如何正确使用组合

How to correctly use composition in 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 uses composition.

  1. Object composition: Object composition is used instead of inheritance (which is used in most of the traditional languages). Object composition means that an object contains object of another object (say Object X) and delegate responsibilities of object X to it. Here instead of overriding functions (as in inheritance), function calls delegated to internal objects.
  2. Interface composition: In interface composition and interface can compose other interface and have all set of methods declared in internal interface becomes part of that interface.

现在具体回答你的问题,你这里说的是界面组成。您还可以在此处查看代码片段: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()
}