Blogger Information
Blog 44
fans 0
comment 1
visits 30691
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月22日——单例模式
时光记忆的博客
Original
854 people have browsed it

单例模式:只能创建一个类的对象

实例

class Test extends School
{
    public function boy()
    {
        $girl = Girl::getInstance();
        $girl1 = Girl::getInstance();
        echo '<pre>';
        var_dump($girl,$girl1);
//        return '我的女朋友'.$girl1->buy();
    }
}

//女朋友类:单例模式
class Girl
{
    private function __construct(){} //构造器私有化
    private function __clone(){} //克隆私有化

    //初始化类的对象
    protected static $instance = null;

    //创建一个外部接口
    public static function  getInstance()
    {
        if(is_null(static::$instance)){
            static::$instance = new static();
        }
        return static::$instance;
    }

    public function buy(){
        return '喜欢买衣服';
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

45654.png

返回只有一个对象

工厂模式


实例

class Factory
{
    public static function create($className)
    {
        $className = strtolower($className);
        switch ($className){
            case 'student':
                return new School;
                break;
            case 'teacher':
                return new Teacher;
                break;
            case 'school':
                return new School;
                break;
            case 'test':
                return new test;
                break;
        }
    }
}

//调用方式
$class = Factory::create('teacher');
return $class->teach();

运行实例 »

点击 "运行实例" 按钮查看在线实例

感觉工厂模式的作用是创建类的对象。并且类的声明如果改变。只需要改变工厂函数中的函数名就好。像是一个静态代理类创建函数对象。



Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!