原型模式就是通过实现 Cloneable
接口的实例上调用 Object 的 clone 方法,复制该类型来创建更多同类型的对象。
并且创建的新类型对象中任何值的更改都不会影响到原来的对象,提供了一种快速建立同种或类似功能的对象。
* 当需要克隆的类中包含其他其他非基本类型时,他们保存的仅仅是对象的用,这也导致克隆后的非基本类型变量和原始对象中相应的变量指向的是同一个对象。这中情况下需要进行深度克隆。
1.抽象原型类
package joeho.net.csdn.blog.Prototype;
public abstract class KeyPortotype implements Cloneable{
private float length;
private float thick;
private String color;
public Object clone(){
Object obj = null;
try{
obj = super.clone();
}catch(CloneNotSupportedException ex){
System.out.println(ex);
}
return obj;
}
public float getLength(){
return length;
}
public float getThick(){
return thick;
}
public String getColor(){
return color;
}
public void setLength(float length)
{
this.length = length;
}
public void setThick(float thick){
this.thick = thick;
}
public void setColor(String color){
this.color = color;
}
}
具体原型类
package joeho.net.csdn.blog.Prototype;
import joeho.net.csdn.blog.Prototype.KeyPortotype;
public class CopperKey extends KeyPortotype {
public CopperKey(){
setColor("黄色");
}
}
package joeho.net.csdn.blog.Prototype;
import joeho.net.csdn.blog.Prototype.KeyPortotype;
public class AluminiumKey extends KeyPortotype {
public AluminiumKey(){
setColor("银色");
}
public static void main(String args[]){
KeyPortotype copperkey = new CopperKey();
System.out.println(copperkey.getColor());
copperkey.setLength(3.1f);
copperkey.setColor("绿色");
KeyPortotype alukey = (KeyPortotype)copperkey.clone();
alukey.setColor("红色");
System.out.println(copperkey.getColor());
System.out.println(alukey.getColor());
//System.out.println(getColor());
}
}