设计模式---原型设计模式
来源:互联网 发布:java long转时间 编辑:程序博客网 时间:2024/05/16 10:51
原型模式属于创建模式,GOF对他的定义是:用原型实例指定创建对象的种类,并且通过拷贝原型创建新对象。
说白了就是对象拷贝,java中有clone方法实现起来非常的容易。
原型设计模式有几个要素:
客户角色:让一个原型克隆自己来得到一个新对象
抽象原型角色:实现自己的clone方法,是具体原型角色的父类
具体原型角色:被复制的对象,是抽象原型角色的子类
/** * */package com.model.prototype;import java.util.HashMap;import java.util.Map;public class PrototypeManager {private static PrototypeManager pm; private Map prototypes = null;private PrototypeManager(){prototypes = new HashMap();}//单例public static PrototypeManager getManager(){if(pm==null){pm = new PrototypeManager();}return pm;}//注册新对象public void register(String name,Object prototype){prototypes.put(name, prototype);}//注销对象public void unregister(String name){prototypes.remove(name);}//public Prototype getPrototype(String name){if(prototypes.containsKey(name)){return (Prototype)((Prototype)prototypes.get(name)).clone();}else{Prototype prototype = null;try {prototype = (Prototype) Class.forName(name).newInstance();register(name, prototype);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return prototype;}}}
通过hashmap来实现注册对象
/** * */package com.model.prototype;public abstract class Prototype implements Cloneable{/* (non-Javadoc) * @see java.lang.Object#clone() */@Overrideprotected Object clone(){Object object = null;try {object = super.clone();} catch (CloneNotSupportedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return object;}}
抽象原型对象,实现自己的clone
原型方法需要复制对象都要实现自己的clone对象,并且clone对象并不安全,所以很少会用上。
它类似于工厂模式但去除了工厂模式繁多的子类
- 设计模式:原型模式
- 设计模式------原型模式
- 设计模式 原型模式
- 设计模式-【原型模式】
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式- 原型模式
- 设计模式:原型模式
- 设计模式 - 原型模式
- 设计模式-原型模式
- 【设计模式】原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 【设计模式】原型模式
- 设计模式----原型模式
- 设计模式------原型模式
- 数量年年增加为啥公交车还是难等
- Javascript中定义类
- Fedora8 远程桌面到 Windows Server 2003 (转)
- Linux下Libpcap源码分析和包过滤机制 (3)
- buildbot安装步骤(仅更新原帖中使用的版本)
- 设计模式---原型设计模式
- Android应用开发之(数据共享) -actionbar
- Linux下Libpcap源码分析和包过滤机制 (4)
- 性能测试总结(一)
- poi 修改EXCEL 内容
- 多发射极晶体管
- import,reload,__import__在python中的区别
- javascript获取可见区域、body对象的宽度和高度
- ubuntu12.04 下挂载qcow2格式镜像的方法