模式是一种很好的方式去描述一种设计,以前没怎么用到模式,现在总结一下php中的模式为以后的工作做点铺垫,php中主要有工厂模式,和单态模式,迭代模式,听他们的名字我们也许可以知道一点什么,
工厂模式:工厂模式是一种类,它具有为您创建对象的某些方法。您可以使用工厂类创建对象,而不直接使用 new。这样,如果您想要更改所创建的对象类型,只需更改该工厂即可。使用该工厂的所有代码会自动更改。这符合送耦合的概念,应为在大的项目中紧密的耦合可能产生很多麻烦尤其是在后期的修改维护中,
interface IUser //声明一个接口
{
function getName();
}
class User implements IUser //实现该接口的类
{
public static function Load( $id ) //创建对象的静态方法,
{
return new User( $id ); //实例化一个对象,
}
public static function Create( )
{
return new User( null );
}
public function __construct( $id ) { }
public function getName() //要实现接口中的方法
{
return "Jack";
}
}
$uo = User::Load( 1 ); //调用类中的静态方法,创建对象 ::可以直接调用
//$uu = User::Create();
//echo $uu;
echo( $uo->getName()."\n" );
单态模式"
class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
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);
}
}
$test = new Example;
// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();
// This will issue an E_USER_ERROR.
$test_clone = clone($test);