原型设计模式
来源:互联网 发布:零基础软件测试 编辑:程序博客网 时间:2024/06/06 19:19
一、原型模式涉及角色
1、prototype :声明一个克隆自身的原型接口。
2、concretrPrototype:实现一个克隆自身的操作。
3、Client:让一个原型克隆自身从而创建一个对象。
二、使用场景和说明
1、当一个系统独立于它的产品的创建、构成和表示时可以使用原型模式;
2、原型模式创建对象比直接new一个对象在性能上要好很多,因为Object类的clone方法是一个本地的方法,它直接操作内存中的二进制流,特别是复制大对象时,性能差别是非常明显的。
3、使用原型模式的另一个好处就是简化对象的创建,使得创建对象就想我们在编辑文档时的复制粘贴一样简单。
1、使用克隆创建对象的时候,构造函数不会被执行,因为对象的赋值是直接调用Object类的clone方法实现的,它在内存中直接复制数据。
2、原型模式其实就是一种拷贝机制,分为深拷贝和浅拷贝执行。一些基本数据类型的拷贝 是为浅拷贝,但是对于数组、容器对象、引用对象都不会拷贝,需要自己实现深拷贝。
三、代码实例
public class Prototype implements Cloneable {
private ArrayList list = new ArrayList();
private String name;
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype.list = (ArrayList) this.list.clone();//深拷贝
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
private ArrayList list = new ArrayList();
private String name;
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype.list = (ArrayList) this.list.clone();//深拷贝
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
}
===========================================================
public class ConcretePrototype extends Prototype {
private String name;
public void show(){
System.out.println("大家好,我是 :"+name);
}
private String name;
public void show(){
System.out.println("大家好,我是 :"+name);
}
}
============================================================
public class Client {
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype();
prototype.setName("原型prototype");
prototype.show();
ConcretePrototype clone001 = (ConcretePrototype) prototype.clone();
clone001.setName("clone001");
clone001.show();
ConcretePrototype clone002 = (ConcretePrototype) prototype.clone();
clone001.setName("clone002");
clone001.show();
}
}
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype();
prototype.setName("原型prototype");
prototype.show();
ConcretePrototype clone001 = (ConcretePrototype) prototype.clone();
clone001.setName("clone001");
clone001.show();
ConcretePrototype clone002 = (ConcretePrototype) prototype.clone();
clone001.setName("clone002");
clone001.show();
}
}
阅读全文
0 0
- 设计模式:原型模式
- 设计模式------原型模式
- 设计模式 原型模式
- 设计模式-【原型模式】
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式- 原型模式
- 设计模式:原型模式
- 设计模式 - 原型模式
- 设计模式-原型模式
- 【设计模式】原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 【设计模式】原型模式
- 设计模式----原型模式
- 设计模式------原型模式
- 想成为机器学习工程师?自学如何入门?
- c++ erase 会使迭代器失效
- C#委托
- Mysql的distinct,concat, group_concat等的用法
- 神经网络,深度学习
- 原型设计模式
- Different Circle Permutation HDU
- js小游戏----俄罗斯方块
- 组合数的几种计算方法
- HackerEarth The Grass Type
- 关联查询
- AE开发中实现Control中的各种图形工具的方法
- js实现简单计算器(样式酷炫)
- okhttp的二次封装(基本使用)