Less Design Patterns
单例-Singleton
单例模式的作用就是保证在整个应用程序的生命周期中,任何一个时刻,
单例类的实例都只存在一个,同时这个类还必须提供一个访问该类的全局访问点。
常见使用实例:数据库连接器;日志记录器(如果有多种用途使用多例模式);锁定文件。
code
singletonTrait.php
<?php
/**
* Trait singletonTrait
*/
namespace singleton;
trait singletonTrait
{
/**
* @var static
*/
protected static $instance = null;
/**
* MTool_SingletonTrait constructor.
*/
private function __construct()
{
}
/**
* 防止被克隆
*/
private function __clone()
{
}
/**
* 防止被反序列化
*/
private function __wakeup()
{
}
/**
* @return static Singleton
*/
final public static function instance()
{
if (static::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
api.php
<?php
namespace singleton;
include_once('./singletonTrait.php');
/**
* Class Api
* @package singleton
*/
class api
{
use singletonTrait;
public function __construct()
{
}
public function test()
{
echo 'test' . PHP_EOL;
}
}
echo api::instance()->test();