原型模式
2016-01-07 22:14
267 查看
package prototype; import java.util.Date; /** * 羊 * * @author zhangjianbin * */ public class Sheep2 implements Cloneable { private String name; private Date birthdays; public Sheep2() { super(); } public Sheep2(String name, Date birthdays) { super(); this.name = name; this.birthdays = birthdays; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthdays() { return birthdays; } public void setBirthdays(Date birthdays) { this.birthdays = birthdays; } /** * 让该类俱有克隆功能 深克隆 * 通过对象序列化 和反序列化也可以实现深克隆 */ @Override protected Object clone() throws CloneNotSupportedException { Object obj = super.clone(); Sheep2 s = (Sheep2) obj; s.birthdays = (Date) this.birthdays.clone(); // 克隆属性对象 ,实现深克隆 return obj; } }
package prototype; import java.util.Date; /** * 羊 * * @author zhangjianbin * */ public class Sheep implements Cloneable { private String name; private Date birthdays; public Sheep() { super(); } public Sheep(String name, Date birthdays) { super(); this.name = name; this.birthdays = birthdays; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthdays() { return birthdays; } public void setBirthdays(Date birthdays) { this.birthdays = birthdays; } /** * 让该类俱有克隆功能 (浅克隆) */ @Override protected Object clone() throws CloneNotSupportedException { Object obj = super.clone(); return obj; } }
public static void main(String[] args) throws CloneNotSupportedException { // 浅克隆 shallowClone(); // 深克隆 deepClone(); } private static void deepClone() throws CloneNotSupportedException { Date date = new Date(); Sheep2 s1 = new Sheep2("羊", date); /** * 浅克隆对象 俱有相同的属性,也引用相同的对象地址 */ Sheep2 s2 = (Sheep2) s1.clone(); System.err.println(s1.getBirthdays()); date.setTime(1212121212L); System.err.println(s2.getBirthdays()); } private static void shallowClone() throws CloneNotSupportedException { Date date = new Date(); Sheep s1 = new Sheep("羊", date); /** * 浅克隆对象 俱有相同的属性,也引用相同的对象地址 */ Sheep s2 = (Sheep) s1.clone(); System.err.println(s1.getBirthdays()); date.setTime(1212121212L); System.err.println(s2.getBirthdays()); } }
相关文章推荐
- POJ1080 Human Gene Functions 题解&代码
- Mybatis启动递归层次太多导致Stackoverflow
- SBT编译入门
- Learn More Study Less `my notes`
- LeetCode OJ:Peeking Iterator(peeking 迭代器)
- 离散--第三章--一阶逻辑
- 属性动画中的插值器和估值器
- 属性动画中的插值器和估值器
- 遥望布达拉——DAY12 觉巴村-荣许兵站
- js中的日历插件
- 【Android View】Android中View对触摸事件的处理和传递dispatchTouchEvent、onInterceptTouchEvent
- C++编程练习——用递归法将一个整数N转换成字符串
- break和continue
- K8S中pod在挂载volume时出现FailedMount错误(exit status 32)
- (iota)regetnIotgnirtS.8
- Storm基本概念
- HTML——如何在html中插入视频
- 从今天起,坚持写博客
- C# using 三种使用方式
- java ArrayList数据对象按排序值大小倒叙排序