prototype

package prototype;

public class GirlFriend implements Cloneable
{
private String name;
private int age;

public void setAge(int age) {
this.age = age;
}

public void setName(String name)
{
this.name = name;
}

public String toString()
{
return name+" 年龄是: "+age;
}

public GirlFriend clone() throws CloneNotSupportedException
{
return (GirlFriend) super.clone();
}
}


package prototype;

public class Boy implements Cloneable
{
private String name;
private GirlFriend gf ;

public void setName(String name)
{
this.name = name;
}
public GirlFriend getGF()
{
return gf;
}
public Boy(String name)
{
this.name = name;
gf = new GirlFriend();
gf.setAge(18);
gf.setName("小芳");
}
public String toString()
{
return name+" 的女朋友是:"+gf;
}
public Boy clone() throws CloneNotSupportedException
{
Boy boy = (Boy)super.clone();
boy.gf = gf.clone();
return boy;
}
}


package prototype;

public class Test
{
public static void main(String[] args) throws CloneNotSupportedException
{
Boy boy = new Boy("张三");
System.out.println(boy+" "+boy.hashCode());

Boy b = boy.clone();
b.getGF().setAge(20);
System.out.println(b+" "+b.hashCode());
System.out.println(boy+" "+boy.hashCode());
}

}
/*
* 原型模式主要是clone 深克隆和浅克隆,深克隆就是要将应用的对象也拷贝进来
* 他们的引用对象不同。而浅克隆只拷贝引用,也就是说他们引用的对象还是同一个。
* 深拷贝中,类中就必须将引用的对象拷贝一份,可以在clone方法中拷贝 也可以用
* 一个私有的构造方法拷贝,但是必须在clone方法中给他赋值。
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值