java设计模式之单例模式

什么是单例

  • 保证类在内存中只有一个对象。
  • 对象是new出来的,因此也就是说在程序中只能new一次对象

 

单例实现的基本步骤

1》声明一个类,类中有一个静态属性,类型与类名相同     

2》把空参构造方法声明为私有

3》在类中提供一个公共静态访问方法来返回该对象实例

单例的多种写法

写法一 饿汉式

class Singleton{

    private static Singleton instance = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){

       return instance;

    }

}

写法二 懒汉式

class Singleton{

    private static Singleton instance;

   

    private Singleton(){}

   

    public static Singleton getInstance(){

       if(instance == null){

           instance = new Singleton();

       }

       return instance;

    }

}

写法三 另一种简单的写法 (饿汉式2.0)

class Singleton{

    public static final Singleton instance = new Singleton();

    private Singleton(){}

}

 

 

饿汉式和懒汉式的区别

  • 饿汉式是空间换时间,懒汉式是时间换空间
  • 在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象
  • 如果考虑线程安全问题,用饿汉式
  • 如果不考虑线程安全问题,用懒汉式
posted @ 2018-12-22 01:07  expworld  阅读(103)  评论(0编辑  收藏  举报