# 单例模式
[TOC]
在实际的开发中,绝大部分的服务性质的类都会设计成单例模式
所谓的单例模式,就是类只有一个对象,外部要使用该类的对象,通过调用一个类方法实现。
## 单例模式特点
* 1、单例类只能有一个实例。
* 2、单例类必须自己创建自己的唯一实例。
* 3、单例类必须给所有其他对象提供这一实例。
## 单例模式实现
关键代码:保证构造函数是私有的。
~~~
/**
* 饿汉式单例模式
* @author lzq31
*
*/
public class Service2 {
private static Service2 service = new Service2();
private Service2() {
}
public static Service2 getInstance() {
return service;
}
}
~~~
~~~
/**
* 懒汉式单例模式
* @author lzq31
*
*/
public class Service {
private static Service service;
private Service() {
}
public static Service getInstance() {
if (null == service) {
service = new Service();
}
return service;
}
}
~~~
## 单例模式的检测
~~~
//当Demo为单例模式时
public class Demo {
private static Demo demo = new Demo();
private Demo() {}
public static Demo getInstance() {
return demo;
}
public int a = 1;
}
public class Demo2 {
public static void main(String[] args) {
Demo demo = Demo.getInstance();
Demo demo2 = Demo.getInstance();
demo.a = demo.a + 1;
System.out.println(demo.a);
System.out.println(demo2.a);
}
}
//当Demo不为单例模式的时候
public class Demo {
public int a = 1;
}
public class Demo2 {
public static void main(String[] args) {
Demo demo = new Demo();
Demo demo2 = new Demo();
demo.a = demo.a + 1;
System.out.println(demo.a);
System.out.println(demo2.a);
}
}
~~~