类与对象(PHP5)之九:模式(Patterns)
日期:2006-09-26 作者:喜腾小二 来源:PHPChina
模式是最好的实践和设计的描述方法。它给普通的编程问题展示一个可变的解决方案。 工厂模式(Factory) 工厂模式允许在运行的时间实例化一个对象。自从工厂模式命名以来,制造一个对象是可能的。
例子 19-23.工厂方法 (Factory Method) PHP代码如下:
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'); } } } ?>
在类中允许定义一个驱动器在不工作时被加载的方法。如果类例子是一个数据库抽象类,可以象如下这样加载一个MySQL和SQLite驱动 PHP代码如下:
php $mysql = Example::factory('MySQL'); // Load a MySQL Driver $sqlite = Example::factory('SQLite'); // Load a SQLite Driver ?>
单独模式(Singleton) 单模式适用于需要一个类的单独接口的情况。最普通的例子是数据库连接。这个模式的实现 允许程序员构造一个通过许多其他对象轻松地访问的单独接口。 例子
19-24.单模式函数(Singleton Function) PHP代码如下:
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代码如下:
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. ?>
|
|
<<<返回技术中心