zoukankan      html  css  js  c++  java
  • 静态延迟绑定

    <?php
    
    /**
     * 静态工厂方法
     * 如果我们有多个子类需要静态 实例化(见注册表模式),但是我们又不想在每一个子类中都写一个创建对象的方法。
     * 那么写在超类中可以吗?
     * 请看下面:
     */
    abstract class DomainObject {
        public static function create() {
            //return new self();
            return new static();
        }
    }
    
    class User extends DomainObject{
    }
    
    class Document extends DomainObject{
    }
    
    //通过Document去调用create方法,但是实际create方法内部的new self()会尝试实例化Domainbject,而不是Document类
    //原因在于self不是指调用上下文,而是指的是解析上下文,解析,顾名思义,self在DomainObject类中的create方法内部,所以self就指向了DomainObject类,所以它才会去尝试实例化DoaminObject类,与我们的想法背道而驰。
    //static关键字可以解决这个问题,static指的是调用上下文,create()方法有Document类调用,所以该次调用的static就绑定到了Document类,从而达到了我们的目地。
    $obj = Document::create();
    
    var_dump($obj);
  • 相关阅读:
    HDU 4005 The war
    #undef
    [转载] #define new DEBUG_NEW
    [转载]常用正则表达式
    [百科]
    [转载]
    [转载]
    [转载]
    [百科]
    [转载]VC6中的文件后缀
  • 原文地址:https://www.cnblogs.com/mtima/p/3180937.html
Copyright © 2011-2022 走看看