第一篇 生成及初始化对象 第五章 - 原型模式

  书接前文,如果我们需要较多的“秋思”对象,需要反复地生成并初始化它们。这些重复性的工作可以简化吗?
  继续优化代码。

// 秋思
public class QiuSi implements Cloneable {

  private String a, b, c, x, y, z;

  // 建造方法(1)
  public QiuSi first(String a, String b, String c) {
    this.a = a;
    this.b = b;
    this.c = c;
    return this;
  }

  // 建造方法(2)
  public QiuSi second(String x, String y, String z) {
    this.x = x;
    this.y = y;
    this.z = z;
    return this;
  }

  // 原型方法
  @Override
  public QiuSi clone() throws CloneNotSupportedException {
    return (QiuSi) super.clone();
  }

  /* Getters and Setters */

}

  我们使QiuSi类实现了java.lang.Cloneable标记接口,还覆写了java.lang.Object#clone()原型方法(二者缺一不可)。
  原型方法和建造方法有些许相似之处,它们的返回类型都是QiuSi。不同的是,建造方法返回了当前对象(this),原型方法返回了另一个对象。
  原型方法以当前对象为原型,直接在内存中复制出了一个全新的对象。这是一种更简捷的对象生成方式,省去了从头构造和初始化的过程。
  优化效果如下。

// 测试类
public class Test {

  public void test() throws Exception {
    // 生成并初始化对象
    QiuSi obj1 = new QiuSi();
    obj1.first("枯藤", "老树", "昏鸦")
       .second("小桥", "流水", "人家");
    // 再来一个
    QiuSi obj2 = obj1.clone();
  }

}

  需要补充的是,如果原型对象含有引用类型(此处的String除外)的成员变量,需要自定义级联复制方法。
  如下所示。

// 夕阳
public class XiYang implements Cloneable {

  @Override
  public XiYang clone() throws CloneNotSupportedException {
    return (XiYang) super.clone();
  }

}

// 秋思
public class QiuSi implements Cloneable {

  private XiYang sun;// 引用类型的成员变量

  // 原型方法
  @Override
  public QiuSi clone() throws CloneNotSupportedException {
    return (QiuSi) super.clone();
  }

  // 级联复制方法
  public QiuSi cloneDeep() throws Exception {
    QiuSi obj = (QiuSi) super.clone();
    if (this.sun != null) {
      obj.sun = this.sun.clone();
    }
    return obj;
  }

  /* Getters and Setters */

}
posted on 2025-03-23 13:49  星辰河岳  阅读(24)  评论(0)    收藏  举报