Go语言类的继承缺陷案例

2021-07-16  本文已影响0人  鸿雁长飞光不度

虽然GO语言通过interface结合蕴含式定义属性能够实现类的继承效果,但是还是有不足之处的,比如下面同样的逻辑用PHP和go运行效果就不一样。

type BinLog interface {
    insert()
    update()
    Dispatch()
}

type Base struct {
}

func (b *Base) insert() {
    fmt.Println("base insert")
}

func (b *Base) update() {
    fmt.Println("base update")
}

func (b *Base) Dispatch() {
    b.insert()
    b.update()
}
type Sub struct {
    *Base
}
func (s *Sub) insert() {
    fmt.Println("sub insert")
}
func main() {
    var h = &Sub{
        &Base{},
    }
    h.Dispatch()
}
// 输出 ---
//base insert
//base update

//Process finished with exit code 0
class Base {

    public function Dispatch()
    {
        $this->insert();
        $this->update();
    }

    protected function insert()
    {
        echo __CLASS__ .__FUNCTION__ . PHP_EOL;
    }

    protected function update()
    {
        echo __CLASS__ .__FUNCTION__ . PHP_EOL;
    }

}
class Sub extends Base {

    protected function insert()
    {
        echo __CLASS__ .__FUNCTION__ . PHP_EOL;
    }
}
(new Sub())->Dispatch();

//-- 输出
//Subinsert
//Baseupdate

//Process finished with exit code 0
上一篇 下一篇

猜你喜欢

热点阅读