프로그래밍/golang

ultimate in go (6)- grouping

나도한강뷰 2023. 1. 24. 00:53

grouping(그룹핑)

상태에 의한 그룹핑

type Animal struct {
    Name     string
    IsMammal bool
}
func (a *Animal) Speak() {
    fmt.Println("UGH!",
        "My name is", a.Name,
        ", it is", a.IsMammal,
        "I am a mammal")
}
type Dog struct {
    Animal
    PackFactor int
}
func (d *Dog) Speak() {
    fmt.Println("Woof!",
        "My name is", d.Name,
        ", it is", d.IsMammal,
        "I am a mammal with a pack factor of", d.PackFactor)
}
type Cat struct {
    Animal
    ClimbFactor int
}
func (c *Cat) Speak() {
    fmt.Println("Meow!",
        "My name is", c.Name,
        ", it is", c.IsMammal,
        "I am a mammal with a climb factor of", c.ClimbFactor)
}
  • 여기까지는 문제업다.
    animals := []Animal{
      Dog{
          Animal: Animal{
              Name: "Fido",
              IsMammal: true,
          },
          PackFactor: 5,
      },
      Cat{
          Animal: Animal{
              Name: "Milo",
              IsMammal: true,
          },
          ClimbFactor: 4,
      },
    }
    for _, animal := range animals {
          animal.Speak()
      }
  • 이코드는 컨파일 되지 않는다.
  • 여기부분에서 animals를 통해서 dog와 cat을 그룹핑해주게 되는데, 이건 go에서 지원하지 않는다.
  • 구조체 내의 공통된 필드를 통해서 그루핑하는것을 권장하지 않는다.
  • 나쁜예시이다.

행동에의한 그룹핑

  • 좋은 예시이다.
  • 인터페이스를 활용하였다.
  • 미리 구성할 필요가없이,컴파일러는 컴파일 타임에 인터페이스와 인터페이스의 action을 자동식별한다
  • 어떤 행동을 할지는 고려해야된다.
type Speaker interface {
    Speak()
}
type Dog struct {
    Name       string
    IsMammal   bool
    PackFactor int
}
func (d Dog) Speak() {
    fmt.Println("Woof!",
        "My name is", d.Name,
        ", it is", d.IsMammal,
        "I am a mammal with a pack factor of", d.PackFactor)
}
type Cat struct {
    Name        string
    IsMammal    bool
    ClimbFactor int
}
func (c Cat) Speak() {
    fmt.Println("Meow!",
        "My name is", c.Name,
        ", it is", c.IsMammal,
        "I am a mammal with a climb factor of", c.ClimbFactor)
}
func main() {
    speakers := []Speaker{
        Dog{
            Name:       "Fido",
            IsMammal:   true,
            PackFactor: 5,
        },
                Cat{
            Name:       "Milo",
            IsMammal:   true,
            ClimbFactor: 4,
        },
    }
    for _, spkr := range speakers {
        spkr.Speak()
    }
}
  • speaker 인터페이스를 통해서 행동 speak를 할줄 알아야지 speaker의 일원이 될 수 있다는것을 명시해준다.
  • dog는 dog의 정보를, cat은 cat의 정보를 가지고 있다
  • dog는 dog의 speak정보를, cat은 cat의 speak정보를 가지고있다.
  • speakers를 통해서 speaker의 그룹을 만들고 그 내부는 speak할 수 있는 애들로 그룹핑해준다.