PHP面向对象-单列模式

WBOY
Release: 2016-06-23 13:32:43
Original
1296 people have browsed it

单例模式,在PHP面向对象中应用的比较广泛, 通常为了节省资源,在性能方面上,代码重用性上考虑,使用设计模式是很不错的选择, 比如数据库操作类系统类库等,通常开源代码都会使用单列模式去设计完成,使用单列模式的优点很明显, 可以保证每个类生成实体的唯一性,性能方面有所提高.

<?phpheader ("Content-Type:text/html; charset=utf8");/** * php设计模式 * 三:单列模式 * */class Sigle{    protected static $instanc = null;    protected function __construct(){    }    public static function getInstan(){        if(self::$instanc === null){            self::$instanc = new self;        }        return self::$instanc;    }    private function __clone(){        echo 'conle';    }}$obj1 =  Sigle::getInst();$obj2 = Sigle::getInst();if($obj1 === $obj2){    echo '是一个对象';}else{    echo '不是一个对象';}
Copy after login

解释: 从列子中可以看出,  把构造函数__construct,__clone私有化, 目的是防止new和克隆一个新的对象, 然后开放getInstace这个公共的操作,让其调用保证这个对象的唯一性.




Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!