单例模式概念
在面向对象的编程中,要求一个类有且仅存在一个实例,提供一个全局的访问方法,避开构造函数,提供一种机制来实现单一实例,
这就是单例模式(Singleton模式)。另因为在as3中无法操作线程,因此我们无需考虑多线程情况下的单例。
单例模式分为懒汉式和饿汉式,懒汉式就是延加载即需要时才创建对象,饿汉式就是定义全局变量时就创建对象;
对于多线程语言推荐使用饿汉式。
---------------------------------------------------------------下边列出as的几种单例模式------------------------------------
单例模式1:饿汉模式
package com.singleton.example
{
public class Singleton1
{
private static var _instance:Singleton1 = new Singleton1();
public function Singleton1()
{
if(_instance)
{
throw new Error("只能用getInstance()来获取实例");
}
}
public static function getInstance():Singleton1
{
return _instance;
}
}
}
单例模式2:懒汉模式
package com.singleton.exmaple
{
public class Singleton5
{
private static var _singleton:Singleton5 = null;
public function Singleton5()
{
if(_singleton == null)
{
trace ("ok");
}
else
{
throw new Error("do not function");
}
}
public static function getInstance():Singleton5
{
if(_singleton == null)
{
_singleton = new Singleton5();
}
return _singleton;
}
public function doSomething():void
{
trace ("dosomething");
}
}
}
单例模式3:内部类
package com.singleton.exmaple
{
public class Singleton4
{
private static var _instance:Singleton4;
public function Singleton4($singletoner:Singletoner)
{
if($singletoner == null)
{
throw new Error("只能用getInstance()来获取实例");
}
}
public static function getInstance():Singleton4
{
if(_instance == null)
{
_instance = new Singleton4(new Singletoner());
}
return _instance;
}
}
}
internal class Singletoner
{
}
单例模式4:设置标志位
package com..singleton.example
{
public class Singleton2
{
private static var _singleton:Boolean = true;
private static var _instance:Singleton2;
public function Singleton2()
{
if(_singleton)
{
throw new Error("只能用getInstance()来获取实例");
}
}
public static function getInstance():Singleton2
{
if(_instance == null)
{
_singleton = false;
_instance = new Singleton2();
_singleton = true;
}
return _instance;
}
}
}
单例模式5:回调函数
package com.singleton.example
{
public class Singleton3
{
private static var singleton:Singleton3;
public function Singleton3(caller:Function=null)
{
if(caller != hidden)
{
throw new Error("只能用getInstance()来获取实例");
}
if(Singleton3.singleton != null)
{
throw new Error("只能用getInstance()来获取实例");
}
}
public static function getInstance():Singleton3
{
if(singleton == null)
{
singleton = new Singleton3(hidden);
}
return singleton;
}
private static function hidden():void
{
}
}
}