设计模式23篇:原型模式
来源:互联网 发布:美国读研gpa算法 编辑:程序博客网 时间:2024/06/05 20:04
定义:
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
类图:
原型模式浅拷贝:
public class Prototype implements Cloneable { public Prototype clone() { Prototype prototype = null; try { prototype = (Prototype) super.clone(); } catch (CloneNotSupportedException e) { // TODO: handle exception e.printStackTrace(); } return prototype; }}
public class ConcretePrototype extends Prototype { public void show() { System.out.println("原型模式实现类"); }}
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub ConcretePrototype cp = new ConcretePrototype(); for (int i = 0; i < 10; i++) { ConcretePrototype clonecp = (ConcretePrototype)cp.clone(); clonecp.show(); } }}
原型模式深拷贝:
public class Person implements Cloneable{ public String _mname; public Person() { _mname = "Nick"; } public Person clone() { Person _mPerson = null; try { _mPerson = (Person) super.clone(); // prototype._mList = this._mList; } catch (CloneNotSupportedException e) { // TODO: handle exception e.printStackTrace(); } return _mPerson; }}
public class Prototype implements Cloneable { Person _mPerson = new Person(); public Prototype clone() { Prototype prototype = null; try { prototype = (Prototype) super.clone(); prototype._mPerson = (Person)this._mPerson.clone(); } catch (CloneNotSupportedException e) { // TODO: handle exception e.printStackTrace(); } return prototype; }}
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub ConcretePrototype cp = new ConcretePrototype(); for (int i = 0; i < 10; i++) { ConcretePrototype clonecp = (ConcretePrototype)cp.clone(); clonecp.show(); System.out.println(clonecp._mPerson._mname); } }}
注意:
使用原型模式复制对象不会调用类的构造方法。因为对象的复制是通过调用Object类的clone方法来完成的,它直接在内存中复制数据,因此不会调用到类的构造方法,和所有的方法,只clone基本数据类型。
0 0
- 设计模式23篇:原型模式
- 设计模式:原型模式
- 设计模式------原型模式
- 设计模式 原型模式
- 设计模式-【原型模式】
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式- 原型模式
- 设计模式:原型模式
- 设计模式 - 原型模式
- 设计模式-原型模式
- 【设计模式】原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 【设计模式】原型模式
- 设计模式----原型模式
- java源码分析--Enumeration接口和Iterator接口
- 自动释放池简单原理
- CWHArray模版类
- img标签详解
- Tab选项卡切换
- 设计模式23篇:原型模式
- Fragment加Viewpager的使用小结
- JSP技术概述
- java面向对象中对属性和方法的封装
- Android使用AnysnTask强求数据
- online_judge_1503
- the java_home environment variable is not defined correctly
- 机器学习实战 第三章 决策树 学习笔记
- Android自定义视图二:用Canvas和Paint绘制折线图