1. 簡單工廠模式:
簡單工廠模式(Simple Factory Pattern):定義一個工廠類,它可以根據參數的不同返回不同類的實例,被創建的實例通常都具有共同的父類。因為在簡單工廠模式中用于創建實例的方法是靜態(static)方法,因此簡單工廠模式又被稱為靜態工廠方法(Static Factory Method)模式,它屬于類創建型模式。
~~~
/**
* 簡單工廠模式與工廠方法模式比較。
* 簡單工廠又叫靜態工廠方法模式,這樣理解可以確定,簡單工廠模式是通過一個靜態方法創建對象的。
*/
abstract class Fruit{
private $name;
// Force Extending class to define this method
abstract protected function getName();
abstract protected function setName($name);
// Common method
public function printName() {
print $this->getName() . "\n";
}
}
class Apple extends Fruit{
function __construct(){
$this->name = "Apple";
}
}
class Banana extends Fruit{
function __construct(){
$this->name = "Banana";
}
}
/*
class Factory{
static function createFruit($classname){
return new $classname();
}
}
*/
class Factory{
static function createFruit($classname){
if($classname == "Apple"){
return new Apple();
}else if($classname == "Banana"){
return new Banana();
}
return null;
}
}
//測試
Factory::createFruit("Apple");
Factory::createFruit("Banana");
~~~