设计模式
2022-10-19 08:48:30内容摘要
设计模式,使用设计模式是促进最佳实践和良好设计的好办法。设计模式可以提供针对常见的编程问题的灵活的解决方案。
文章正文
设计模式
使用设计模式是促进最佳实践和良好设计的好办法。设计模式可以提供针对常见的编程问题的灵活的解决方案。
工厂模式
工厂模式(Factory)允许你在代码执行时实例化对象。它之所以被称为工厂模式是因为它负责“生产”对象。工厂方法的参数是 你要生成的对象对应的类名称。
Example #1 调用工厂方法(带参数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <code><?php class Example { // The parameterized factory method public static function factory( $type ) { if ( include_once 'Drivers/' . $type . '.php' ) { $classname = 'Driver_' . $type ; return new $classname ; } else { throw new Exception ( 'Driver not found' ); } } } ?></code> |
按上面的方式可以动态加载drivers。如果Example类是一个数据库抽象类,那么 可以这样来生成MySQL和 SQLite驱动对象:
1 2 3 4 5 6 7 | <code><?php // Load a MySQL Driver $mysql = Example::factory( 'MySQL' ); // Load a SQLite Driver $sqlite = Example::factory( 'SQLite' ); ?></code> |
单例
单例模式(Singleton)用于为一个类生成一个唯一的对象。最常用的地方是数据库连接。 使用单例模式生成一个对象后,该对象可以被其它众多对象所使用。
Example #2 单例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <code><?php class Example { // 保存类实例在此属性中 private static $instance ; // 构造方法声明为private,防止直接创建对象 private function __construct() { echo 'I am constructed' ; } // singleton 方法 public static function singleton() { if (!isset(self:: $instance )) { $c = __CLASS__ ; self:: $instance = new $c ; } return self:: $instance ; } // Example类中的普通方法 public function bark() { echo 'Woof!' ; } // 阻止用户复制对象实例 public function __clone() { trigger_error( 'Clone is not allowed.' , E_USER_ERROR); } } ?></code> |
这样我们可以得到一个独一无二的Example类的对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 | <code><?php // 这个写法会出错,因为构造方法被声明为private $test = new Example; // 下面将得到Example类的单例对象 $test = Example::singleton(); $test ->bark(); // 复制对象将导致一个E_USER_ERROR. $test_clone = clone $test ; ?></code> |
代码注释