结构图
模式说明
类设计
模式说明
- 原型模式其实是从一个对象再创建另外一个相同的对象,而且不需要知道创建对象的细节。
- 在初始化信息不发生变化的情况下,使用clone既隐藏了对象创建的细节,又能对性能大大提高。等于是不用重新对象初始化,而是动态获得对象运行时状态。
- 如果对象的字段类型是值类型,则对该字段执行逐位复制,如果字段类型是引用类型,则默认的clone只复制引用而不复制引用的对象。
- String是一种拥有值类型特点的特殊引用类型。
- 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
public static void main(String[] args) throws Exception {
ConcretePrototype cp =
new ConcretePrototype(1, 2.0f, 3.0d, (short) 4,
5L, (byte) 6, '7', "8string");
Object clone = cp.clone();
clone.toString();
}
类设计
public class ConcretePrototype implements Cloneable {
private int d_int;
private float d_float;
private double d_double;
private short d_short;
private long d_long;
private byte d_byte;
private char d_char;
private String d_String;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public ConcretePrototype(int d_int, float d_float, double d_double,
short d_short, long d_long, byte d_byte, char d_char, String string) {
super();
this.d_int = d_int;
this.d_float = d_float;
this.d_double = d_double;
this.d_short = d_short;
this.d_long = d_long;
this.d_byte = d_byte;
this.d_char = d_char;
d_String = string;
}
@Override
public String toString() {
String str = getClass().getCanonicalName() + ":" + d_int + ","
+ d_float + "," + d_double + "," + d_short + "," + d_long + ","
+ d_byte + "," + d_char + "," + d_String;
System.out.println(str);
return str;
}
}