设计模式-单例模式

作用:保证一个类只有一个实例存在,并提供全局访问

结构:(- :表示私有 + 公开)

实现:

1、饿汉模式实现,在类中就已经实例化。

public class Singleton {

	//将构造方法私有化,不允许外部直接创建
	private Singleton(){}
	
	private static Singleton instance = new Singleton();//实例
	
	//提供一个获取实例的方法,防止被其他类操作
	public static Singleton getInstance(){
		return instance;
	}
}

备注:

static修饰的成员变量和成员方法独立于该类的任何对象,不需要实例化就可以使用,被类的所有实例共享,在类加载时,根据类名在运行时的数据区中存放.

 

2、懒汉模式——线程不安全

public class Singleton2 {
	private Singleton2() {
	}
	private static Singleton2 instance;
	
	public static Singleton2 getInstance(){
		if(instance == null){
			instance = new Singleton2();
		}
		return instance;
	}
}


备注:仅在调用getInstance方法时实例化。所以在调用后加载速度慢。

 

3、懒汉模式---线程安全

	public static synchronized Singleton3 getInstance(){
		if(instance == null){
			instance = new Singleton3();
		}
		return instance;
	}

备注:添加线程锁。用关键字synchronized实现当它锁定一个方法或者一个代码块的时候,同一时刻最多只有一个线程执行这个段代码。

测试:

public class Test {

	public static void main(String[] args) {
		/**
		 * 饿汉模式:加载类时比较慢 运行时快 线程安全
		 */
		System.out.println("-------饿汉模式----------");
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();
		if(s1==s2){
			System.out.println("s1和s2是同一个实例");
		}else{
			System.out.println("s1和s2不是同一个实例");
		}
		
		/**
		 * 懒汉模式 加载类时比较快 运行时比较慢  线程不安全
		 */
		System.out.println("-------懒汉模式----------");
		Singleton2 s3 = Singleton2.getInstance();
		Singleton2 s4 = Singleton2.getInstance();
		if(s3==s4){
			System.out.println("s3和s4是同一个实例");
		}else{
			System.out.println("s3和s4不是同一个实例");
		}
		
		/**
		 * 懒汉模式 加载类时比较快 运行时比较慢  加入线程锁线程安全安全
		 */
		System.out.println("-------懒汉模式 优化----------");
		Singleton3 s5 = Singleton3.getInstance();
		Singleton3 s6 = Singleton3.getInstance();
		if(s5==s6){
			System.out.println("s5和s6是同一个实例");
		}else{
			System.out.println("s5和s6不是同一个实例");
		}
	}
}
 

思考:

1、在Android开发中,当程序启动时系统会创建一个 application对象,用来存储系统的一些信息。当我们重写application,可以在里面定义一些全局变量或方法,通过单例模式,可以在项目中任何地方获取想要的方法或值。
 

终极版:

public class Singleton {
    private static volatile Singleton instance = null;

    private Singleton(){
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值