设计模式学习笔记之单例模式

单例模式:

单例模式是一种常用的且非常简单的一种设计模式。它的核心结构只有一个被称为单例类的特殊类。通过单例模式可以保证系统只有一个实例而且容易被外界访问,从而节约系统资源,减少gc的回收内存的压力,避免了一些引起业务逻辑错误的因素。

 

(单例模式类图)

 

单例模式一般有三种模式:

     懒汉式

public class Singleton {

 

   private static Singleton singleton;

  

   /**

    *构造器

    *

    *@authorzhaozb

    *@timeOct12,20133:41:54PM

    */

   private Singleton() {}

  

   /**

    *获取实例

    *

    *@return

    *@authorzhaozb

    *@timeOct12,20133:42:11PM

    */

   public synchronized Singleton getInstance() {

       if(singleton ==null){

          singleton =new Singleton();

       }

      return singleton;

   }

}

在涉及到多线程时需要加Synchronized字段。

 

     饿汉式

    private static Singleton instance =new Singleton();

//  static {

//     instance = new Singleton();

//  }

   

    /**

     *构造器

     */

    private Singleton(){};

   

    /**

     *得到实例

     *

     *@return

     *@authorzhaozb

     *@timeOct12,20133:52:43PM

     */

    public static Singleton getInstance(){

       return instance;

}

     双重锁定

public class Singleton {

   

    private static Singleton instance;

   

    /**

     *私有构造器

     *

     *@authorzhaozb

     *@timeOct12,20133:53:58PM

     */

    private Singleton(){};

   

    public static Singleton getInstance(){

       if(instance ==null){

           synchronized(Singleton.class){

              if(instance ==null){

                  instance =new Singleton();

              }

           }

       }

       return instance;

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值