美文网首页
Go语言类的继承缺陷案例

Go语言类的继承缺陷案例

作者: 鸿雁长飞光不度 | 来源:发表于2021-07-16 15:05 被阅读0次

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

    • 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
    
    • php
    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
    

    相关文章

      网友评论

          本文标题:Go语言类的继承缺陷案例

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