概览
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象

类图

image.png

实例

  1. public class Prototype implements Cloneable{
  2. @Override
  3. protected Prototype clone() throws CloneNotSupportedException {
  4. Prototype p=null;
  5. try{
  6. p=(Prototype)super.clone();
  7. }catch (ClassCastException e){
  8. e.printStackTrace();
  9. }
  10. return p;
  11. }
  12. }
  1. public class ConcretePrototype extends Prototype{
  2. private String field;
  3. public ConcretePrototype(String filed){
  4. this.field=filed;
  5. }
  6. @Override
  7. public String toString() {
  8. return field;
  9. }
  10. }
  1. public class Client {
  2. public static void main(String[] args) throws CloneNotSupportedException {
  3. Prototype obj1=new ConcretePrototype("abc");
  4. Prototype obj2=obj1.clone();
  5. Prototype obj3=obj1.clone();
  6. System.out.println(obj1);
  7. System.out.println(obj2);
  8. System.out.println(obj3);
  9. }
  10. }
  1. abc
  2. abc
  3. abc