设计模式-创建型-原型模式(Prototype)
2016-08-04 21:49
453 查看
定义
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象所需条件
原型类要实现CloneAble接口原型类或其子类要实现clone方法
优点
原型模式创建对象比new一个对象的性能强的多,尤其是大对象,因为Object类的clone方法是本地方法,直接操作内存中的二进制流简化对象的创建
浅克隆、深克隆
浅克隆:只克隆对象中的基本数据类型和String,而不会克隆数组、容器、引用对象等。换言之,浅复制仅仅复制所考虑的对象,而不复制它所引用的对象深克隆:把要克隆的对象所引用的对象都克隆了一遍
类图
package com.vapy.creator.Prototype; /** * * @author vapy * */ import java.util.ArrayList; public abstract class Prototype implements Cloneable { protected ArrayList<String> list = new ArrayList<String>(); @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } public abstract void show(); }
package com.vapy.creator.Prototype; /** * * @author vapy * */ public class ShallowClone extends Prototype { @Override public Prototype clone(){ Prototype prototype = null; try { prototype = (Prototype)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return prototype; } @Override public void show(){ System.out.println("浅克隆"); } }
package com.vapy.creator.Prototype; /** * * @author vapy * */ import java.util.ArrayList; public class DeepClone extends Prototype { @SuppressWarnings("unchecked") @Override public Prototype clone() { Prototype prototype = null; try { prototype = (Prototype)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } prototype.list = (ArrayList<String>) this.list.clone(); return prototype; } @Override public void show(){ System.out.println("深克隆"); } }
package com.vapy.creator.Prototype; /** * * @author vapy * */ public class Client { public static void main(String[] args) { ShallowClone cp = new ShallowClone(); ShallowClone clonecp = (ShallowClone) cp.clone(); clonecp.show(); System.out.println(clonecp.list == cp.list); DeepClone cp2 = new DeepClone(); DeepClone clonecp2 = (DeepClone) cp2.clone(); clonecp2.show(); System.out.println(clonecp2.list == cp2.list); } }
本文代码可在github查看:点击此处
相关文章推荐
- 面向对象设计模式之Prototype原型模式(创建型)
- 设计模式之原型法(ProtoType)----对象创建型模式
- JAVA设计模式(05):创建型-原型模式(Prototype)
- 跟着实例学习设计模式(7)-原型模式prototype(创建型)
- java语言实现创建型设计模式—原型模式(Prototype)
- 设计模式五:Prototype原型模式——对象创建型模式
- PHP设计模式:创建型之原型模式(Prototype)
- 设计模式(五):PROTOTYPE原型模式 -- 创建型模式
- 设计模式05: Prototype 原型模式(创建型模式)
- C#面向对象设计模式学习笔记(5) - Prototype 原型模式(创建型模式)
- 面向对象设计模式之Prototype原型模式(创建型)
- 设计模式笔记--创建型模式之四--原型prototype
- 设计模式学习总结4 - 创建型4 - Prototype原型模式
- 设计模式学习之原型模式(Prototype,创建型模式)(5)
- C#面向对象设计模式纵横谈(6):Prototype 原型(创建型模式)
- [设计模式-创建型]原型(Prototype)
- 设计模式(四)原型模式Prototype(创建型)
- 设计模式(四)原型模式(Prototype)-创建型
- 设计模式(四)、PROTOTYPE(原型)---对象创建型模式
- [导入]C#面向对象设计模式纵横谈(6):Prototype 原型模式(创建型模式).zip(9.56 MB)