【Java笔记】14 单例设计模式
一、什么是单例设计模式
- 采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法
- 两种方式:饿汉式和懒汉式
二、饿汉式
类加载时创建,不存在线程安全问题
- 构造器私有化,防止直接new
- 类的内部创建对象 static
- 向外暴露一个静态的公共方法
饿汉式可能造成创建了对象但是没有使用
public class SingleTon01 {
public static void main(String[] args) {
A a = A.getInstance(); //通过方法获取对象
}
}
class A{
private String name;
// 2. 在类的内部直接创建,此时外部不可用
private static A a = new A("aaa");
// 保证只能创建一个对象
// 1. 将构造器私有化
private A(String name){
this.name = name;
}
// 3. 提供一个公共的static方法,返回对象
// 设为静态才能保证不创建对象能直接调用这个方法,因此2中的对象是static的
public static A getInstance(){
return a;
}
}
三、懒汉式
懒汉式只有当用户使用getInstance()时,才能返回对象,再次调用时,会返回上次创建的cat对象,存在线程安全问题
public class SingleTon02 {
public static void main(String[] args) {
Cat instance = Cat.getInstance();
}
}
// 希望在程序运行过程中,只能创建一个Cat对象
class Cat{
private String name;
// 2.定义一个static静态属性对象
private static Cat cat;
// 1. 构造器私有化
private Cat(String name){
this.name = name;
}
// 3. 提供一个public的static方法,可以返回一个Cat对象
public static Cat getInstance() {
if(cat == null) {
cat = new Cat("aaa");
}
return cat;
}
}
四、实例
Runtime工具类的源码
public class Runtime {
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}