用懒汉单例模式模式和饿汉单例模式模式模拟产生本班的班长并写出测试类
时间: 2023-04-12 12:01:41 浏览: 118
java 单例模式(懒汉式与饿汉式)
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是用懒汉单例模式和饿汉单例模式模拟产生本班的班长的代码:
懒汉单例模式:
```java
public class ClassPresident {
private static ClassPresident instance;
private String name;
private ClassPresident(String name) {
this.name = name;
}
public static synchronized ClassPresident getInstance(String name) {
if (instance == null) {
instance = new ClassPresident(name);
}
return instance;
}
public String getName() {
return name;
}
}
```
饿汉单例模式:
```java
public class ClassPresident {
private static ClassPresident instance = new ClassPresident("张三");
private String name;
private ClassPresident(String name) {
this.name = name;
}
public static ClassPresident getInstance() {
return instance;
}
public String getName() {
return name;
}
}
```
以下是测试类的代码:
```java
public class TestClassPresident {
public static void main(String[] args) {
// 测试懒汉单例模式
ClassPresident president1 = ClassPresident.getInstance("李四");
ClassPresident president2 = ClassPresident.getInstance("王五");
System.out.println(president1.getName()); // 输出:李四
System.out.println(president2.getName()); // 输出:李四(因为已经有一个实例了)
// 测试饿汉单例模式
ClassPresident president3 = ClassPresident.getInstance();
ClassPresident president4 = ClassPresident.getInstance();
System.out.println(president3.getName()); // 输出:张三
System.out.println(president4.getName()); // 输出:张三(因为已经有一个实例了)
}
}
```
希望这个回答能够帮到你!
阅读全文