桥接模式

Bridge模式基于类的最小设计原则,通过使用封装、聚合及继承等行为让不同的类承担不同的职责。
它的主要特点是把抽象(Abstraction)与行为实现(Implementation)分离开来,从而可以保持各部分的独立性以及应对他们的功能扩展

package bridge

//Bridge模式基于类的最小设计原则,通过使用封装、聚合及继承等行为让不同的类承担不同的职责。
//它的主要特点是把抽象(Abstraction)与行为实现(Implementation)分离开来,从而可以保持各部分的独立性以及应对他们的功能扩展

//抽象接口
type DisplayImpl interface {
    rawOpen() string
    rawPrint() string
    rawClose() string
}

//字符串展示结构体
type StringDisplayImpl struct {
    str string
}

//实现DispalyImpl接口:行为实现
func (self *StringDisplayImpl) rawOpen() string {
    return self.printLine()
}
func (self *StringDisplayImpl) rawPrint() string {
    return "|" + self.str + "|\n"
}

func (self *StringDisplayImpl) rawClose() string {
    return self.printLine()
}
func (self *StringDisplayImpl) printLine() string {
    str := "+"
    for _, _ = range self.str {
        str += string("-")
    }
    str += "+\n"
    return str
}

//通过聚合实现抽象和行为实现的分离
type DefaultDisplay struct {
    impl DisplayImpl
}

func (self *DefaultDisplay) open() string {
    return self.impl.rawOpen()
}
func (self *DefaultDisplay) print() string {
    return self.impl.rawPrint()
}

func (self *DefaultDisplay) close() string {
    return self.impl.rawClose()
}

func (self *DefaultDisplay) Display() string {
    return self.open() +
        self.print() +
        self.close()
}

//通过聚合实现抽象和行为实现的分离
type CountDisplay struct {
    *DefaultDisplay
}

func (self *CountDisplay) MultiDisplay(num int) string {
    str := self.open()
    for i := 0; i < num; i++ {
        str += self.print()
    }
    str += self.close()
    return str
}

package bridge

import "testing"

func TestBridge(t *testing.T) {
    d1 := DefaultDisplay{&StringDisplayImpl{"AAA"}}
    expect := "+---+\n|AAA|\n+---+\n"
    if result := d1.Display(); result != expect {
        t.Errorf("Expect result to equal %s, but %s.\n", expect, result)
    }

    //行为实现和抽象分离了
    d2 := CountDisplay{&DefaultDisplay{&StringDisplayImpl{"BBB"}}}
    expect = "+---+\n|BBB|\n+---+\n"
    if result := d2.Display(); result != expect {
        t.Errorf("Expect result to equal %s, but %s.\n", expect, result)
    }

    expect = "+---+\n|BBB|\n|BBB|\n+---+\n"
    if result := d2.MultiDisplay(2); result != expect {
        t.Errorf("Expect result to equal %s, but %s.\n", expect, result)
    }
}



你可能感兴趣的:(桥接模式)