建造者模式
建造者模式是使用多个简单对象一步一步创建出一个复杂对象,属于创建型模型,常用链式调用的方式进行对象的创建。本文只介绍使用静态内部类的Builder模式。
public class People {
private String eye;
private String hand;
private String mouth;
private String foot;
public People(){
this(new Builder());
}
private People(Builder builder) {
this.eye = builder.eye;
this.hand = builder.hand;
this.mouth = builder.mouth;
this.foot = builder.foot;
}
@Override
public String toString() {
return "People{" +
"eye='" + eye + '\'' +
", hand='" + hand + '\'' +
", mouth='" + mouth + '\'' +
", foot='" + foot + '\'' +
'}';
}
public static class Builder {
private String eye;
private String hand;
private String mouth;
private String foot;
public Builder setEye(String eye) {
this.eye = eye;
return this;
}
public Builder setHand(String hand) {
this.hand = hand;
return this;
}
public Builder setMouth(String mouth) {
this.mouth = mouth;
return this;
}
public Builder setFoot(String foot) {
this.foot = foot;
return this;
}
public People build() {
return new People(this);
}
}
}
在需要创建对象的类内部引入静态内部类Builder,由于静态内部类只能直接使用外部类的静态成员变量。所以在Builder内部类中需要添加与外部类相同的成员变量,并在给变量赋值完成后返回当前Builder对象,达到链式调用的目的。最后调用build( )
方法创建对象。此种内部类Builder模式比较简介,OkHttpClient就是通过此种方式创建。
原型模式
原型模式主要主要用于对象的复制,对象的复制有深拷贝和浅拷贝两种,浅拷贝在复制目标对象时会复制目标对象的非基本类型数据,当目标对象存在非基本类型数据时,只会复制非基本类型的引用。深拷贝是只指复制目标所有数据到一个新的对象,包括目标对象内部的非基本数据类型也是会复制成一个全新的对象,而不仅仅是复制引用。
浅拷贝
实现cloneAble
接口,该接口无任何需要实现的方法。只是作为clone标记。重写Object的clone()
方法。
public class People implements Cloneable {
private String name;
private String age;
private String sexal;
private People parent;
@Override
protected People clone() throws CloneNotSupportedException {
return (People) super.clone();
}
}
通过clone()
创建的新对象和原来的对象中的parent
属性为同一个引用,也就是改变其中一个对象的paren
t,另一个对象的parent
也会改变。
深拷贝
深拷贝连同目标对象的非基本类型一起拷贝,而不是直接引用。通过重写clone()
方法达到目的。
public class People implements Cloneable {
private String name;
private String age;
private String sexal;
private People parent;
@Override
protected People clone() throws CloneNotSupportedException {
People people = (People) super.clone();
if (parent != null) {
people.parent = this.parent.clone();
}
return people;
}
}
小结
实现深拷贝还可以使用序列化。
final 修饰变量无法被序列化。
clone()
不会调用类的构造方法,当构造方法简单,不含太多逻辑上,new要快点,反之,clone()
会快点,取决于实际情况。