要使用单例模式,首先需要你声明一个类似getInstance的一个方法,返回实例,并且在构造函数中加以判断,不允许第二个实例出现。示例代码如下:
public static function getInstance ( ) : ModelLocator { if ( modelLocator == null ) { modelLocator = new ModelLocator ( ); } return modelLocator; }
限制构造函数:
public function ModelLocator ( ) { if ( modelLocator != null ) { throw new Error ( "Only one instance should be instantiated" ); } }