java 创建型设计模式 中的原型模式
时间: 2023-12-26 19:27:41 浏览: 38
原型模式是一种创建型设计模式,它允许通过复制现有对象来创建新对象,而无需通过实例化类来创建。在Java中,可以使用原型模式来创建对象,而不必依赖于构造函数或者new关键字。
以下是一个使用原型模式创建对象的示例:
```java
// 创建一个实现了Cloneable接口的原型类
class Prototype implements Cloneable {
private String name;
public Prototype(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
// 重写clone方法,实现对象的复制
@Override
public Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
// 使用原型模式创建对象
public class PrototypePatternExample {
public static void main(String[] args) {
// 创建原型对象
Prototype prototype = new Prototype("原型对象");
try {
// 复制原型对象
Prototype clone = prototype.clone();
clone.setName("复制对象");
// 输出原型对象和复制对象的名称
System.out.println("原型对象的名称:" + prototype.getName());
System.out.println("复制对象的名称:" + clone.getName());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
```
运行以上代码,将会输出以下结果:
```
原型对象的名称:原型对象
复制对象的名称:复制对象
```