单例模式(单子模式)
单例模式就是一个类只能创建一个对象
优点:①实现数据共享 ②项目安全
缺点:①降低并发性(并发性与安全性是相对的,项目安全,则并发性低)
②增加了耦合性
单例模式分成:饥汉模式(饿汉模式):
①有静态全局变量并且对其进行初始化了
②构造方法是私有化的
③获取对象采用静态方法
饱汉模式(懒汉模式):
①有静态全局变量,但是没有初始化
②构造方法私有化
③在获取对象的静态方法中初始化静态全局变量
代码:
/*单例–饥汉(饿汉)模式/
public class Singleton1 {
public int count;
private static Singleton1 instance=new Singleton1(10); //静态全局变量,并进行初始化了
private Singleton1(int n){
//对外不提供构造方法:在类的外部不能创建对象
this.count = n;
System.out.println("count = " + this.count);
}
public int getCount(){
return this.count;
}
public static Singleton1 getInstance(){
//为了获得Singleton1的对象,只能采用静态方法,因为对象还未创建,无法使用实例方法
return instance.instance; //调用instance所指对象的instance属性,还是对象的地址,形成一个环
}
}
/测试类/
public class TestSingleton1{
public static void main(String[] args){
Singleton1 a1 = Singleton1.getInstance(); //静态方法可以通过类调用,
Singleton1 a2 = Singleton1.getInstance();
System.out.println("a1.count = " + a1.getCount());
System.out.println("a2.count = " + a2.getCount());
System.out.println("a2 == a1 is " + (a1 == a2)); //指的是同一个对象
}
}
懒汉模式/饱汉模式:用的时候再创建对象
/修改饥汉模式/
public class Singleton1 {
public int count;
private static Singleton1 instance; //静态全局变量,但是没有初始化,用的时候在初始化
private Singleton1(int n){ //私有的构造方法
this.count=count;
}
public static Singleton1 getInstance() {
if (instance == null) { //使用的时候判断有没有创建,如果没有,就创建对象
instance = new SingleTon();
}
return instance; //然后创建的对象
}
}
适用场景:
对配置文件修改的类,可以使用单例模式,每次都是同一个对象对配置文件进行修改。
对数据库操作的类,每次都是同一个对象,不需要重复创建数据库连接等操作