php 3种常见设计模式

1、工厂模式

<?php
namespace Facebab;
class Factory {
    static function createDatabase () {
        return new Database();
    }

}

$db = Facebab\Factory::createDatabase();
$db->fetchOne();

2、单例模式

<?php
namespace Facebab;
class Singleton {
    
    private static $db = null;
    private __construct() {

    }

    static function getInstance() {

        if (self::$db != null) {
            return self::$db;
        } else {
            self::$db = new self();
            return self::$db;
        }

    }

    private __clone() {

    }
}

3、注册模式

 

<?php
namespace Facebab;
class Register {
    
    private static $objects = array();

    static function set($alias,$object) {
        self::$objects[$alias] = $object;
    }

    static function _unset($alias) {
        unset(self::$objects[$alias]);
    }

    static function get($name) {
        return self::$objects[$name];
    }
}

Register::set('db1',$db);
$db = Facebab\Register::get('db1');

 

你可能感兴趣的:(php 3种常见设计模式)