原型模式的定义:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。属于创建型模式,原型模式一般不单独使用,常和其他模式一起使用,比直接使用new新建对象性能要好得多,因为object类的方法是直接操作内存的中二进制流,尤其在复制大对象,性能显著。因此要重复新建对象是,可以考虑使用原型。
主要特点:
- 实现Cloneable接口。
- 重写Object类中的clone方法。
根据上述,我们定义一个原型,实现Cloneable,并重写clone()。
public class Prototype implements Cloneable {
@Override
protected Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
} catch (CloneNotSupportedException exception) {
exception.printStackTrace();
}
return prototype;
}
}
定义一个具体的类,继承原型。
public class BirdType extends Prototype {
public void fly(){
System.out.println("I can fly");
}
}
在创建一个实例后,后面需要创建的实例可以通过现有实例俩创建。
public class Main {
public static void main(String[] args) {
Prototype prototype = new BirdType();
BirdType birdType = (BirdType) prototype.clone();
birdType.fly();
}
}
网友评论