Go言語入門 / golang 入門 デザインパターン Composite

f:id:nasust:20161122141513p:plain The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) CC3.0

こんにちはnasustです。 wikipediaComposite パターン - Wikipediaを参考にGo言語 / golangで実装しました。

package main

import "fmt"

type FileInterface interface {
    DefaultMethod(depth int)
    GetChildren() []FileInterface
    AddComponent(c FileInterface) bool
    RemoveComponent(c FileInterface) bool
}

type File struct {
    name string
}

func NewFile(name string) *File {
    return &File{name}
}

func (self *File) DefaultMethod(depth int) {
    for i := 0; i < depth; i++ {
        fmt.Print("    ")
    }
    fmt.Println("file:", self.name)
}

func (self *File) GetChildren() []FileInterface {
    return nil
}

func (self *File) AddComponent(c FileInterface) bool {
    return false
}

func (self *File) RemoveComponent(c FileInterface) bool {
    return false
}

type Folder struct {
    name     string
    fileList []FileInterface
}

func NewFolder(name string) *Folder {
    return &Folder{name, []FileInterface{}}
}

func (self *Folder) DefaultMethod(depth int) {
    for i := 0; i < depth; i++ {
        fmt.Print("    ")
    }
    fmt.Println("Folder:", self.name)
    for _, item := range self.fileList {
        item.DefaultMethod(depth + 1)
    }
}

func (self *Folder) GetChildren() []FileInterface {
    return self.fileList
}

func (self *Folder) AddComponent(c FileInterface) bool {
    self.fileList = append(self.fileList, c)
    return true
}

func (self *Folder) RemoveComponent(c FileInterface) bool {
    for i := 0; i < len(self.fileList); i++ {
        item := self.fileList[i]
        if c == item {
            self.fileList = append(self.fileList[:i], self.fileList[:i+1]...)
            return true
        }
    }
    return false
}

func main() {
    root := NewFolder("root")
    usr := NewFolder("usr")
    varf := NewFolder("var")
    home := NewFolder("home")
    user1 := NewFolder("user1")
    file1 := NewFile("file1")

    root.AddComponent(usr)
    usr.AddComponent(varf)
    root.AddComponent(home)
    home.AddComponent(user1)
    user1.AddComponent(file1)
    root.DefaultMethod(0)
}

実行結果

Folder: root
    Folder: usr
        Folder: var
    Folder: home
        Folder: user1
            file: file1

wikipediaの例と全く同じように実装できます。


Go言語 / golang 入門 目次に戻る

広告を非表示にする