Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《Android源码设计模式解析与实战》第2章-单例模式 #11

Open
panyz opened this issue Jun 2, 2017 · 0 comments
Open

《Android源码设计模式解析与实战》第2章-单例模式 #11

panyz opened this issue Jun 2, 2017 · 0 comments
Assignees

Comments

@panyz
Copy link
Owner

panyz commented Jun 2, 2017

前言

此笔记摘抄于《Android源码设计模式解析与实战》一书

单例模式的定义

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

单例模式的使用场景

确保一个类有且只有一个对象的场景,避免了产生多个对象消耗过多的资源,或者某种类型的对象只应该有且只有一个。例如,创建一个对象需要消耗的资源过多,如要访问IO和数据库等资源,这时候就要考虑使用单例模式。

单例模式的实现

  1. 构造函数不对外开放,一般为private;
  2. 通过一个静态的方法或者枚举返回单例类的对象;
  3. 确保单例类的对象有且只有一个,尤其是在多线程的情况下;
  4. 确保单例类对象在反序列化时不会重新构建对象。

单例模式的简单示例

  • 饿汉式
	private static Singleton singleton = new Singleton();
	//构造函数私有
	private Singleton(){}
	//公有的静态函数,对外暴露获取单例对象的接口
	public static Singleton getInstance(){
		return singleton;
	}
}
@panyz panyz self-assigned this Jun 2, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant