简单理解懒汉式和饿汉式

单例设计模式

饿汉式

:一个类只能创建一个对象

  1. 私有化构造器
  2. 在类的内部创建一个类的实例,且为static
  3. 私有化对象,通过公共方法调用
  4. 此公共方法只能通过类来调用,因为设置的是static,同时类的实例也是static

饿汉先创建好:

	package bank;
	
	public class TestSingleton {
	    public static void main (String[] args){
	            Singleton s1 = Singleton.getInstance();
	            Singleton s2 = Singleton.getInstance();
	            System.out.println(s1 == s2); //true
	
	    }
	}
	
	class Singleton{
	    //1.私有化构造器
	    private Singleton(){
	    }
	    //2.在类中创建一个类的实例,私有化,静态的
	    private static Singleton instance = new Singleton();
	    // 3.通过公共方法调用,此公共方法只能类调用,因为设置了 static
	    public static Singleton getInstance(){
	        return instance;
	    }
	}
懒汉式
  1. 私有化构造器

  2. 创建一个私有的实例static 先不实例化 为 null

  3. 通过公共方法调用 static 在方法里面进行判断,if = null
    实例化 !=null 直接return

    class Singleton{
            //1.私有化构造器
            private Singleton(){}
            //2.创建一个私有的实例为static 且值设置为null
        private static Singleton instance = null;
            //3.通过公共方法调用,static
        public static Singleton getInstance(){
            if (instance == null){
                instance = new Singleton();
            }
            return instance;
        }
    }
    

懒汉式:用的时候创建

懒汉式:可能出现线程安全问题,
线程安全的懒汉式

public class SingleDemo {
	    private static SingleDemo s = null;
	    private SingleDemo(){}
	    public static  SingleDemo getInstance(){
	        /*如果第一个线程获取到了单例的实例对象,
	         * 后面的线程再获取实例的时候不需要进入同步代码块中了*/
	        if(s == null){
	            //同步代码块用的锁是单例的字节码文件对象,且只能用这个锁
	            synchronized(SingleDemo.class){
	                if(s == null){
	                    s = new SingleDemo();
	                }
	            }
	        }
	        return s;
	    }
	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值