PHP 之设计模式学习笔记 - 单例模式(自用)
目的:
节约资源,避免浪费资源
实现:
构造方法私有化
class Test
{
protected static $type;
/**
* Factory constructor.
*/
private function __construct()
{
}
/**
* 静态方法实现私有化
* @return Factory
*/
public static function getData()
{
if (self::$type) {
return self::$type;
}else{
self::$type = new self();
return self::$type;
}
}
/**
* @param $type
* @return mixed
*/
public function addData($type)
{
return $type;
}
}
调用:
$factory = Test::getData();
$bicycle = $factory->addData("bicycle"); //调用类中方法