什么是单例模式?
单例模式是java设计模式的一种,这个模式的目的就是保证某一个类只有一个实例存在。比如我们java中的DataSource数据源就是需要只有一个实例,是单例模式的一种实现。单例模式由于在内存中只有一个实例,减少了内存的开销,当我们频繁的创建和销毁实例时,并且该模式还能避免对资源的多重占用。
单例模式中我们主要分为饿汉模式和懒汉模式,以下介绍这两种模式以及实现方式。
package 设计模式;/*** @author zq** 单例模式-饿汉模式*/
//把这类设定成单例模式
class Singleton{//唯一实例的本体,在内部创建好实例private static Singleton instance = new Singleton();//获取实例的方法public static Singleton getInstance(){return instance;}//禁止外部new实例private Singleton(){}
}
public class ThreadDemo11 {public static void main(String[] args) {//此时s1和s2是同一个对象Singleton s1 = Singleton.getInstance();Singleton s2 = Singleton.getInstance();//但是但凡我们再new时,就会有新的对象。//措施,将该类的构造方法设为private}
}
注意: 饿汉模式实现时有一下注意点,需要我们掌握。
package 设计模式;/*** @author zq* 饿汉模式*/
class SingletonLazy{//volatile修饰该变量,解决指令重排序问题volatile private static SingletonLazy instance = null;public static SingletonLazy getInstance(){if (instance==null){//第一次创建时才加锁。synchronized (SingletonLazy.class){if (instance==null){//饿汉模式,只有需要时才去new一个对象instance = new SingletonLazy();}}}return instance;}
}
public class ThreadDemo12 {public static void main(String[] args) {SingletonLazy s1 = SingletonLazy.getInstance();SingletonLazy s2 = SingletonLazy.getInstance();System.out.println(s1==s2);}
}
注意: 该代码在线程安全解决方式中有一些注意点