设计模式-单例模式-Java实现

1、单例模式

都2020年了,现在打游戏已经是件很平常的事了。有些游戏中,会有一些特殊的角色,他们在游戏中是唯一存在的,譬如一些特定的世界 BOSS,不同的玩家因为副本容量不够大进入到不同的副本中,打的却是同一个 BOSS。


这就是单例模式,顾名思义就是整个程序中只有一个实例对象。
单例模式有两种:

  1. 饿汉模式
  2. 饱汉模式

2、实例解析

假设要在程序中有类 Singleton,现在要通过单例模式使得程序中只能有一个该类的实例,主程序如下:

public class Main {
    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("程序结束");
    }
}

i、饿汉模式

饿汉模式,因为是饿汉,所以很着急想要获取这个实例,因此在类加载时就生成对应实例:

public class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton() {
        System.out.println("生成了一个实例");
    }
    public static Singleton getInstance(){
        return singleton;
    }
}

通过将构造函数的修饰符定义为 private 来避免用户新建对象。

ii、饱汉模式

饱汉模式,因为是饱汉,所以一点都不着急获取这个实例,因此在用到这个实例的时候再去生成对应实例:

public class Singleton {
	private static Singleton singleton;
	private Singleton(){
		System.out.println("生成了一个实例");
	}
	public static Singleton getInstance(){
		if(singleton==null){
			singleton = new Singleton();
		}
		return singleton;
	}
}

乍一看这么写没什么问题,但是其实是有问题的,在高并发的情况下,也许会多次执行 singleton = new Singleton(); 语句,从而产生问题,因此需要加锁:

public class Singleton {
	private static Singleton singleton;
	private Singleton(){
		System.out.println("生成了一个实例");
	}
	public static Singleton getInstance(){
		if(singleton==null){
			synchronized(Singleton.class){
				if(singleton==null){
					singleton = new Singleton();
				}
			}
		}
		return singleton;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值