| 网站首页 | 文章中心 | 电子书下载 | 矢量图库 | 视频教程 | 素材下载 | 程序代码下载 | JS代码 | 论坛 | 
常用软件类:
|杀毒安全 |联络聊天 |网络软件 |多媒体类 |系统工具 |图形图像 |系统工具 |应用软件 |行业软件
开发设计类:
|动画制作 |图像处理 |3D设计 |操作系统 |站长学院 |网络相关 |WEB设计 |数据库类 |程序开发
PHP5基础教程-类与对象之模式(Patterns)
  模式是最好的实践和设计的描述方法。它给普通的编程问题展示一个可变的解决方案。
工厂模式(Factory)
工厂模式允许在运行的时间实例化一个对象。自从工厂模式命名以来,制造一个对象是可能的。
例子 19-23.工厂方法 (Factory Method)

PHP代码如下:
CODE:
<?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代码如下:
CODE:
<?php
 $mysql 
Example::factory('MySQL'); 
// Load a MySQL Driver
 
$sqlite Example::factory('SQLite'); 
// Load a SQLite Driver
?> 

单独模式(Singleton)
单模式适用于需要一个类的单独接口的情况。最普通的例子是数据库连接。这个模式的实现
允许程序员构造一个通过许多其他对象轻松地访问的单独接口。
例子 19-24.单模式函数(Singleton Function)

PHP代码如下:
CODE:
<?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代码如下:
CODE:
<?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.
?> 

  • 上一篇文章:

  • 下一篇文章: 没有了
  • 相关文章