美文网首页
设计模式之——单例模式

设计模式之——单例模式

作者: q若水 | 来源:发表于2017-11-02 15:39 被阅读19次

单例模式(Singleton)

1.什么是单例模式?

保证一个类只有一个实例,并提供一个访问他的全局访问点。


2.单例模式有那些类型?

(1)饿汉式

package com.singleton;

import static org.hamcrest.CoreMatchers.nullValue;

public class Singleton {

//饿汉式

//构造方法私有化

private Singleton(){

}

//内部提供一个唯一对象实例

private static Singleton  instance =new Singleton();

//提供一个静态方法向外界提供此对象实例

public static Singleton getInstance(){

return instance;

}

}

(2)懒汉式

package com.singleton;

import static org.hamcrest.CoreMatchers.nullValue;

public class Singleton {

//懒汉式

//构造方法私有化

private Singleton(){

}

//内部提供一个唯一对象实例

private static Singleton instance=null;

//提供一个静态方法向外界提供此对象实例

public static  Singleton getInstance(){

if (instance== null) {

instance=new  Singleton();

}

return instance;

}

}

3 饿汉式和懒汉式有什么区别?优缺点?

(1)饿汉式类加载就创建对象(在虚拟机启动的时候就会创建,),以后不在改变若不使用要这个对象的话,会占用内存;饿汉式是线程安全的;

(2)懒汉式延时加载,使用时才创建对象,但是多线程时可能会创建多个对象,懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的;

相关文章

网友评论

      本文标题:设计模式之——单例模式

      本文链接:https://www.haomeiwen.com/subject/engwpxtx.html