美文网首页
Golang设计模式,组合模式

Golang设计模式,组合模式

作者: FredricZhu | 来源:发表于2019-09-26 13:37 被阅读0次

    两个例子,一个组合运动员,一个树。

    package composite
    
    // region start composite swimmer demo
    type ITrainer interface {
        Train()
    }
    
    type ISwimmer interface {
        Swim()
    }
    
    type CompositeSwimmer struct {
        ITrainer
        ISwimmer
    }
    
    type Athlete struct{}
    
    func (a *Athlete) Train() {
        println("Training")
    }
    
    type Swimmer struct{}
    
    func (b *Swimmer) Swim() {
        println("Swimming")
    }
    
    // endregion end composite swimmer demo
    
    // region start tree demo
    type Tree struct {
        LeafValue int
        Left      *Tree
        Right     *Tree
    }
    
    // endregion end tree demo
    

    测试程序

    package composite
    
    import (
        "testing"
    )
    
    func TestComposite_Swimmer(t *testing.T) {
        swimmer := CompositeSwimmer{
            ITrainer: &Athlete{},
            ISwimmer: &Swimmer{},
        }
    
        swimmer.Train()
        swimmer.Swim()
    }
    
    func TestTree(t *testing.T) {
        root := Tree{
            LeafValue: 0,
            Left: &Tree{
                LeafValue: 20,
                Left:      nil,
                Right:     nil,
            },
            Right: &Tree{
                LeafValue: 20,
                Left:      nil,
                Right: &Tree{
                    LeafValue: 8,
                    Left:      nil,
                    Right:     nil,
                },
            },
        }
    
        println(root.Right.Right.LeafValue)
    }
    
    

    相关文章

      网友评论

          本文标题:Golang设计模式,组合模式

          本文链接:https://www.haomeiwen.com/subject/hafxyctx.html