1、某班需要班长主持班会,应用单例模式(分别用懒汉式单例和饿汉式单例两种实现形式)产生班长,模拟班会举行。
时间: 2024-04-29 22:23:11 浏览: 30
懒汉式单例实现:
```java
public class ClassLeader {
private static ClassLeader instance;
private ClassLeader() {}
public static synchronized ClassLeader getInstance() {
if (instance == null) {
instance = new ClassLeader();
}
return instance;
}
public void presideMeeting() {
System.out.println("班长主持班会");
}
}
public class Main {
public static void main(String[] args) {
ClassLeader leader = ClassLeader.getInstance();
leader.presideMeeting();
}
}
```
饿汉式单例实现:
```java
public class ClassLeader {
private static final ClassLeader instance = new ClassLeader();
private ClassLeader() {}
public static ClassLeader getInstance() {
return instance;
}
public void presideMeeting() {
System.out.println("班长主持班会");
}
}
public class Main {
public static void main(String[] args) {
ClassLeader leader = ClassLeader.getInstance();
leader.presideMeeting();
}
}
```
阅读全文