1、什么是原型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
实现了在运行期建立和删除原型。
2、原型模式的代码实现
1、构建抽象原型类
这一步也可以省略,在具体原型类中直接实现 java
提供的 Conleable
接口,实现 clone
方法
public abstract class Prototype {
abstract Prototype myClone();
}
2、构建具体原型类
/**
* 或者直接实现 Conleable 接口,重写 clone 方法
*/
public class ConcretePrototype extends Prototype {
private String filed;
public ConcretePrototype(String filed) {
this.filed = filed;
}
@Override
Prototype myClone() {
return new ConcretePrototype(filed);
}
@Override
public String toString() {
return filed;
}
}
3、创建原型对象
public class Client {
public static void main(String[] args) {
Prototype prototype = new ConcretePrototype("abc");
// 如果是实现了 Conleable 接口,就调用 clone 方法
Prototype clone = prototype.myClone();
System.out.println(clone.toString());
}
}
3、原型模式的优缺点
优点:
- 性能提高
- 逃避构造函数的约束
缺点:
- 配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候
- 必须实现 Cloneable 接口
**注意事项:**与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的。浅拷贝实现 Cloneable,重写 clone,深拷贝是通过实现 Serializable 读取二进制流。