任务要求:自行设计一个能够应用单例模式或者原型模式的案例(注意不能选择教材上的案例),画出类图并用代码实现
时间: 2025-06-27 19:04:16 浏览: 9
### 单例模式与原型模式的自定义示例
#### 自定义单例模式
单例模式的核心在于确保某个类只有一个实例,并提供全局访问点。以下通过一个实际场景——日志记录器(Logger),展示如何设计并实现单例模式。
##### UML 类图
```plaintext
+-------------------+
| Logger |
+-------------------+
| - instance: Logger|
+-------------------+
| + getInstance(): Logger|
| + log(message: String): void|
+-------------------+
```
##### 实现代码
```java
public class Logger {
private static volatile Logger instance; // 使用volatile关键字确保线程安全
private Logger() { // 私有化构造函数防止外部实例化
if (instance != null) {
throw new RuntimeException("Use `getInstance()` method to create an object.");
}
}
public static Logger getInstance() { // 提供全局访问点
if (instance == null) {
synchronized (Logger.class) {
if (instance == null) {
instance = new Logger();
}
}
}
return instance;
}
public void log(String message) { // 日志记录功能
System.out.println(Thread.currentThread().getName() + ": " + message);
}
}
```
上述代码实现了懒汉式单例模式,利用双重检查锁定机制[^1]确保线程安全性。
---
#### 自定义原型模式
原型模式的核心在于通过克隆现有对象来创建新对象,从而减少性能开销。以下通过一个实际场景——图形绘制工具(Shape Drawing Tool),展示如何设计并实现原型模式。
##### UML 类图
```plaintext
+-------------------+
| Shape |
+-------------------+
| - id: String |
+-------------------+
| + draw(): void |
| + clone(): Shape |
+-------------------+
+-------------------+ +-------------------+
| Circle |<----->| Rectangle |
+-------------------+ +-------------------+
| | | |
+-------------------+ +-------------------+
```
##### 实现代码
```java
// 抽象基类
abstract class Shape implements Cloneable {
protected String id;
abstract void draw(); // 子类需实现的具体绘图逻辑
@Override
public Object clone() throws CloneNotSupportedException { // 克隆方法
return super.clone();
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle with ID: " + this.id);
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a rectangle with ID: " + this.id);
}
}
// 测试类
public class PrototypeDemo {
public static void main(String[] args) {
try {
Shape cachedCircle = new Circle();
cachedCircle.id = "CIRCLE_001";
Shape clonedCircle = (Shape) cachedCircle.clone(); // 创建副本
clonedCircle.draw();
Shape cachedRectangle = new Rectangle();
cachedRectangle.id = "RECTANGLE_001";
Shape clonedRectangle = (Shape) cachedRectangle.clone(); // 创建副本
clonedRectangle.draw();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
```
上述代码展示了如何通过`clone()`方法快速复制已有对象,而无需重新初始化[^4]。
---
#### 关联环境的区别
Spring 中的单例模式与 GOF 的单例模式存在显著差异。GOF 单例强调的是在整个 JVM 进程中只存在一个实例,而 Spring 单例则限定于 IoC 容器范围内。这意味着,在多容器环境下,每个容器可能会有自己的单例实例。
---
阅读全文
相关推荐















