两个简单的php设计模式

1.单例模式
不管多少次实例化类,都只有一个实例存在,适合数据库操作
<?php
class my{
	public static $_instance = NULL;
	public static function getInstance(){
		if(self::$_instance == NULL) 
		self::$_instance = new self();
		return self::$_instance;
	}
	public function red(){
		echo "red";
	}
	public function __construct(){
		echo 1;
	}
}
$db = My::getInstance();
$db->red();
$mm = My::getInstance();
$mm->red();
?>

运行结果:两个对象,执行一次构造方法
2.工厂模式
不同处理对象,内部自动分流处理,但对用户来说,只有一个方法,简单方便
interface Hello{
	function say_hello();
}
class English implements Hello{
	public function say_hello(){
		echo "Hello!";
	}
}
class Chinese implements Hello{
	public function say_hello(){
		echo "你好";
	}
}
class speak{
	public static function factory($type){
		if($type == 1) $temp = new English();
		else if($type == 2) $temp = new Chinese();
		else{
			die("Not supported!");
		}
		return $temp;
	}
}
$test = Speak::factory(1);
$test->say_hello();

你可能感兴趣的:(php 设计模式)