xin's blog

Just have a little faith.
  首页  :: 管理

单例模式的三种写法

Posted on 2009-10-28 12:56  greatxin  阅读(1392)  评论(2)    收藏  举报

1.
package  
{
    
    
/**
     * 标准的单例可以扩展,所以不要定义成final类
     * 
@author chancidal
     
*/
    
public class MyClass 
    {
        
//
        private static var m_instance:MyClass;
        
//
        public function MyClass() 
        {
            
        }
        
public static function getInstance():MyClass {
            
if (!m_instance) {
                m_instance 
= new MyClass();
            }
            
return m_instance;
        }
        
public function sayHello():void {
            trace(
"hello,world");
        }
    }
    
}

2.
package  
{
    
    
/**
     * 
     * 
@author chancidal
     
*/
    
public class Ball
    {
        
//
        private static var m_instance:Ball;
        
//
        public function Ball() 
        {
            m_instance 
= this;
        }
        
public static function getInstance():Ball {
            
return m_instance;
        }
        
public function sayHello():void {
            trace(
"hello,world");
        }
    }
    
}

3.
package  
{
    
    
/**
     * 利用包外类限制生成单例类的实例
     * 
@author chancidal
     
*/
    
public class AnotherSingle 
    {
        
//
        private static var m_instance:AnotherSingle;
        
//
        public function AnotherSingle(singletonEnforcer:MyEnforcer) 
        {
            
if (!singletonEnforcer) {
                
throw new Error("Singleton and can only be accessed through Singleton.getInstance()");
            }
        }
        
public static function getInstance():AnotherSingle {
            
if (!m_instance) {
                m_instance 
= new AnotherSingle(new MyEnforcer())
            }
            
return m_instance;
        }
        
public function sayHello():void {
            trace(
"hello,world");
        }
    }
    
}
class MyEnforcer {}