设计模式-单例模式

设计模式-单例模式

一 设计模式概述:
java中设计模式一共23种
是解决某一类问题最行之有效的方法

二 单例设计模式:
解决一个类在内存中仅仅存在一个对象的问题

想要保证对象的唯一性:
1,为了避免其它程序过多的建立该类对象。现金支改程序建立该类对象,即构造函数私有化

2,为了让其它程序能够訪问到该类对象,仅仅好在本类中,自己定义一个对象

3。为了方便其它程序对自己定义对象的訪问。能够对外提供一些訪问方式

实现单例模式的步骤:
1,将构造函数私有化

2,在类中创建一个本类的对象

3,提供一个方法能够获取到该对象

以下是一个学生单例类
这里写图片描写叙述

三 两种单例模式
1。饿汉式:
先初始化对象
该类一进入,就已经创建好了对象
开发使用这样的

class Test
{
    //自己定义对象
    private static Test t = new Test();
    //构造函数私有化
    private Test(){}; 
    //提供getInstance方法
    public static Test getInstance()
    {
        return t;
     }

}

2。懒汉式:
对象是方法被调用时才初始化,也叫对象的延时载入
该类进入内存,对象没有存在,仅仅有调用了getInstance方法时。才建立对象

class Test
{
    //自己定义对象为空
    private static Test t = null;
    //构造函数私有化
    private Test(){}; 
    //提供getInstance方法
    public static synchronized Test getInstance()
    { 
                  if(t == null)
                  {
                      t = new Test();
                  }
           return t; 
    } 
}

缺点:
在cpu调度的时候。可能会出现故障,可能会建立多个对象
解决方式一:
加上synchronized

class Test
{
    private static Test t = null;
    private Test(){}; 
    public static synchronized Test getInstance()
    { 
       return t; 
    } 
}

这样的方案会使得程序效率低

解决方式二:
使用双重推断和synchronized配合。常用这样的方法

class Test
{
    private static Test t = null;
    private Test(){}; 
    public static Test getInstance()
    {
        if(t ==null)
        {
            synchronized(Test.class)
            {
        if(t == null)
            t = new Test();
        }
         }
    }
    return t; 
}
原文地址:https://www.cnblogs.com/zhchoutai/p/7239856.html