用懒汉单例模式模式和饿汉单例模式模式模拟产生本班的班长并画出设计图
时间: 2023-04-12 08:01:46 浏览: 85
好的,让我来回答你的问题。对于懒汉单例模式和饿汉单例模式,它们都是用来创建一个类的唯一实例的设计模式。
懒汉单例模式是在第一次使用时才创建实例,而饿汉单例模式则是在类加载时就创建实例。
下面是用懒汉单例模式和饿汉单例模式模拟产生本班的班长的代码:
懒汉单例模式:
```java
public class ClassPresident {
private static ClassPresident instance;
private ClassPresident() {}
public static synchronized ClassPresident getInstance() {
if (instance == null) {
instance = new ClassPresident();
}
return instance;
}
}
```
饿汉单例模式:
```java
public class ClassPresident {
private static final ClassPresident instance = new ClassPresident();
private ClassPresident() {}
public static ClassPresident getInstance() {
return instance;
}
}
```
对于设计图,我可以提供一个简单的 UML 类图:
```
+-----------------+
| ClassPresident |
+-----------------+
| - instance |
+-----------------+
| + getInstance() |
+-----------------+
```
希望这个回答能够帮到你!