原型模式
通过implements Cloneable接口,该对象可以通过clone实现对象的拷贝.
1.抽象一个手机类,实现cloneable接口
public abstract class Phone implements Cloneable {
private String telephone = "";
public Phone(String telephone) {
this.telephone = telephone;
}
@Override
protected Phone clone() {
try {
return (Phone) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
}
2.华为手机
public class HuaWeiPhone extends Phone {
public HuaWeiPhone(String telephone) {
super(telephone);
}
}
3.测试类
public class Test {
public void test() {
HuaWeiPhone huaWeiPhone1 = new HuaWeiPhone("1323");
HuaWeiPhone huaWeiPhone2 = (HuaWeiPhone) huaWeiPhone1.clone();
System.out.println(huaWeiPhone1 == huaWeiPhone2);
//输出结果为false,说明并不是传值引用 ,两个对象有自己的地址。
}
}