这里主要讲一下单例模式的两种形式,当然还有其他的实现方式
单例模式的作用主要是确保在Java应用中,一个类只用一个实例存在
主要方法是定义一个类,他的构造方法是private的,他的方法都是static的
形式一
在自己的内部定义并实例化一个自己的实例,getInstance()方法是供外部访问本类使用的,可以直接访问。
- /**
- * 单例模式一
- * 一般认为这种形式更安全一些
- */
- public class Singleton {
- private Singleton(){}
- private static Singleton instance = new Singleton();
- private static Singleton getInstance(){
- return instance;
- }
- }
- /**
- * 单例模式二
- */
- public class Singleton2 {
- private static Singleton2 instance = null;
- private static synchronized Singleton2 getInstance(){
- if(instance == null){
- instance = new Singleton2();
- }
- return instance;
- }
- }