1、单例模式
class A
{
private static $_instance = null;
//禁止构造函数,防止被new
private function __construct(){}
//禁止克隆
private function __clone(){}
//禁止序列化
private function __wakeup(){}
public static function getInstance()
{
if(is_null(self::$_instance)){
self::$_instance = new self();
}
return self::$_instance;
}
}
$a = A::getInstance();
2、工厂模式
//定义一个接口
interface Shape
{
public function draw();
}
//定义具体的实现类
class Circle implements Shape
{
public function draw()
{
return "I am a Circle";
}
}
class Square implements Shape
{
public function draw()
{
return "I am a Square";
}
}
//定义一个工厂类
class ShapeFactory
{
const CIRCLE = 'circle';
const SQUARE = 'square';
private $shape;
public function __construct($shape)
{
$this->shape = $shape;
}
public function getShape()
{
switch ($this->shape){
case self::CIRCLE :
return new Circle();
break;
case self::SQUARE :
return new Square();
break;
default:
return null;
}
}
}
//客户端调用
$shape = (new ShapeFactory('circle'))->getShape();
$str = $shape->draw();
var_dump($str);