
常用软件类: |
|杀毒安全 | |联络聊天 | |网络软件 | |多媒体类 | |系统工具 | |图形图像 | |系统工具 | |应用软件 | |行业软件 |
开发设计类: |
|动画制作 | |图像处理 | |3D设计 | |操作系统 | |站长学院 | |网络相关 | |WEB设计 | |数据库类 | |程序开发 |
<?php
class Example
{ public static function factory($type)//The factory method
{ if (include_once 'Drivers/'.$type.'.php')
{ $classname = 'Driver_' . $type;
return new $classname;
}else{ throw new Exception ('Driver not found'); }
}
}
?> <?php
$mysql = Example::factory('MySQL'); // Load a MySQL Driver
$sqlite = Example::factory('SQLite'); // Load a SQLite Driver
?> <?php
class Example
{ // Hold an instance of the class
private static $instance;
private function __construct()//A private constructor;prevents direct creation of object
{ echo 'I am constructed'; }
public static function singleton()// The singleton method
{ if (!isset(self::$instance))
{ $c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example method
public function bark() { echo 'Woof!'; }
// Prevent users to clone the instance
public function __clone(){ trigger_error('Clone is not allowed.',E_USER_ERROR); }
}
?> <?php
$test = new Example; // This would fail because the constructor is private
$test = Example::singleton();// This will always retrieve a single instance of the class
$test->bark();
$test_clone = clone($test); // This will issue an E_USER_ERROR.
?>