java 原型模式的要素
时间: 2023-12-31 09:23:56 浏览: 30
原型模式是一种创建型设计模式,它允许通过复制现有对象来创建新对象,而无需通过实例化类。原型模式的要素包括:
1. 原型接口(Prototype Interface):定义了克隆方法的接口,该方法用于复制现有对象并创建新对象。
2. 具体原型类(Concrete Prototype Class):实现了原型接口,实现了克隆方法来复制自身。
3. 客户端(Client):使用原型对象的客户端代码。
通过使用原型模式,可以避免直接实例化类,而是通过复制现有对象来创建新对象。这样可以提高对象的创建效率,并且可以在运行时动态地添加或删除对象。
以下是一个示例代码,演示了如何使用原型模式创建新对象:
```java
// 原型接口
interface Prototype {
Prototype clone();
}
// 具体原型类
class ConcretePrototype implements Prototype {
private String name;
public ConcretePrototype(String name) {
this.name = name;
}
public Prototype clone() {
return new ConcretePrototype(this.name);
}
public String getName() {
return name;
}
}
// 客户端
public class Client {
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype("原型对象");
ConcretePrototype clone = (ConcretePrototype) prototype.clone();
System.out.println("原型对象的名称:" + prototype.getName());
System.out.println("克隆对象的名称:" + clone.getName());
}
}
```