单例模式(饿汉,懒汉)
单例模式懒汉式和饿汉式的区别
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
饿汉式
package cn.lucky.Singleton;
/**
* @author lucky
*/
public class Hungry {
private Hungry (){
}
private static Hungry hungry = new Hungry();
public static Hungry getInstance(){
System.out.println("instance:"+hungry);
System.out.println("加载饿汉式...");
return hungry;
}
}
懒汉式
package cn.lucky.Singleton;
/**
* @author lucky
*/
public class Lazy {
private static Lazy lazy;
public Lazy() {
}
public static Lazy getInstance(){
if (lazy==null){
lazy=new Lazy();
System.out.println(lazy);
System.out.println("加载懒汉式...");
}
return lazy;
}
}
测试类
package cn.lucky.Singleton;
/**
* @author lucky
*/
public class Test {
public static void main(String[] args) {
Hungry h1 = Hungry.getInstance();
Hungry h2 = Hungry.getInstance();
// System.out.println(h1);
// System.out.println(h2);
Lazy l1 = Lazy.getInstance();
Lazy l2 = Lazy.getInstance();
}
}
思考
private static Hungry hungry = new Hungry();//static如果去掉会如何?
饿汉去掉static
package cn.lucky.Singleton;
/**
* @author lucky
*/
public class Hungry {
public Hungry (){
}
private Hungry hungry = new Hungry();
// public static Hungry getInstance(){
// System.out.println("instance:"+hungry);
// System.out.println("加载饿汉式...");
// return hungry;
// }
}
测试
package cn.lucky.Singleton;
/**
* @author lucky
*/
public class Test {
public static void main(String[] args) {
Hungry hungry = new Hungry();
}
}
报错原因:我们new对象的时候加载Hungry类,类中又new了一个Hungry,无数循环,导致无数个对象在堆中开辟空间,报错OOM,但是由于对象较小,底层优化将对象放在了栈中,因此出现了栈溢出的现象。


浙公网安备 33010602011771号