当前位置:编程学习 > 网站相关 >>

设计模式(1)-创建型-单件(Singleton)模式(个人笔记)

提起设计模式,确实有不少著作讨论它,<<设计模式>>一书理论化很强,我这里干脆整理出一些用代码来体现的实例来说明。
第一个就是Singleton模式,意指始终保证只创建或得到一个唯一的实例。
其代码如下:
提起设计模式,确实有不少著作讨论它,<<设计模式>>一书理论化很强,我这里干脆整理出一些用代码来体现的实例来说明。
第一个就是Singleton模式,意指始终保证只创建或得到一个唯一的实例。
其代码如下:
package com.sql9.created;
/**
 * @author iihero
 */
class SafeSingleton
{
    public static class Holder
    {
        private static SafeSingleton instance = new SafeSingleton();
    }
   
    private SafeSingleton()
    {
        System.out.println("SafeSingleton initialized here....");
    }
   
    public static SafeSingleton getInstance()
    {
        return Holder.instance;
    }
   
}
public class Singleton
{
    private static Singleton _instance;
   
    private Singleton()
    {
    }
   
    public static Singleton getInstance()
    {
        synchronized(Singleton.class)
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
   
    public static void main(String[] args)
    {
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance());
       
        System.out.println(SafeSingleton.getInstance());
        System.out.println(SafeSingleton.getInstance());
    }
}
结果如下:
com.sql9.created.Singleton@c17164
com.sql9.created.Singleton@c17164
SafeSingleton initialized here....
com.sql9.created.SafeSingleton@14318bb
com.sql9.created.SafeSingleton@14318bb
总结:
这里SafeSingleton采取了lazy initialized方式来初始化,只有第一次调用时才会初始化Singleton这个实例。比Singleton类的实现要好一些。不加synchronized()的Singleton在多线程环境下,则会出现问题,可能出现同时初始化的情况。


摘自 iihero@CSD
补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,