2つの簡単なphp設計モード

1288 ワード

1.一例モード
クラスをインスタンス化する回数にかかわらず、データベース操作に適したインスタンスは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つのオブジェクト、1回の構築方法を実行
2.工場モデル
異なる処理対象、内部自動分流処理、しかしユーザーにとって、ただ1つの方法、簡単で便利です
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();