wly603

设计模式----单例模式

一、单例模式(SingleTon)

    保证一个类只有一个实例,并提供一个访问它的全局方法

二、程序示例

单例类
//单例模式

package com;


public class Singleton
{
    private static Singleton instance = null;
    
    //私有化的构造方法,不允许外部通过 new 来产生实例
    private Singleton()
    {
        
    }
    
    public static Singleton getInstance()
    {
        if (instance == null)
        {
            instance = new Singleton();            
        }
        
        return instance;
    }

}

 

测试程序(客户端)
package com;

public class TsetMain 
{
    
    public static void main(String[] args) 
    {
        Singleton a = Singleton.getInstance();
        Singleton b = Singleton.getInstance();
        
        System.out.println("a hashcode:  "+a.hashCode());
        System.out.println("b hashcode:  "+b.hashCode());
        
        System.out.println(a);
        System.out.println(b);

    }

}

 

观察打印输出结果,对比hashcode,可以发现属于同一个对象!

posted on 2012-04-11 19:21  wly603  阅读(170)  评论(0编辑  收藏  举报

导航