读《HeadFirst设计模式》笔记之单例模式
时间: 2018-08-08来源:OSCHINA
前景提要
「深度学习福利」大神带你进阶工程师,立即查看>>>
单例模式: 确保一个类只有一个实例,并提供一个全局访问点。即多次new对象,只能获取同一个对象。
实现方式一:懒汉模式(线程不安全) public class Singleton { private static Singleton instance; private Singleton() {} public Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
实现方式二:饿汉模式(线程安全) public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public Singleton getInstance() { return instance; } }
构造函数是私有的,外部不能直接创建对象,只能通过静态方法getInstance()方法获取对象。

科技资讯:

科技学院:

科技百科:

科技书籍:

网站大全:

软件大全:

热门排行