单例的设计模式
首先我们要知道单例的作用和目的;
目的:就是为了防止我们创建多个对象;一个类只有一个实例;
作用:这样保证了我们创建的实例始终指向这个对象;防止我们创建多个对象;
可以用来储存我们想要的数据.
第一种:在声明变量时实例化,代码如下:
public class Singleton {
private static Singleton instance = new Singleton(); //已经自行实例化
private Singleton(){} //私有的默认构造
public static Singleton getInstance() { //静态工厂方法
return instance;
}
}
第二种:把对象的创建放到方法里面去(也叫懒汉式单例模式),代码如下:
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static synchronized Singleton getInstance() {
//也可以这样写:synchronized public static Singleton getInstance() {
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
各自的优缺点:
第一种模式:
优点:在类加载初始化的时候就创建对象,调用getInstance的时候,没有同步方法,运行时性能较高。
缺点:类加载速度慢,占用太多大的资源空间。
第二种懒汉式:
优点:避免了第一种方式的缺点, 同时,可以在多线程下运行安全。
缺点:因为他使用了锁,在运行中效率慢。