主页 > 开源代码  > 

设计模式——原型模式(PrototypePattern)

设计模式——原型模式(PrototypePattern)

文章目录 一、原型模式定义二、例子2.1 利用Cloneable克隆接口实现的。2.1.1 定义可复制自身的User类2.1.2 定义原型工厂PrototypeFactory2.1.3 使用 2.2 JDK源码——ArrayList 三、其他设计模式

一、原型模式定义

类型: 创建型模式 目的: 用于创建重复的对象,同时又能保证性能。

二、例子 2.1 利用Cloneable克隆接口实现的。 2.1.1 定义可复制自身的User类 public class User implements Cloneable { protected String id; protected String name; public User(String id, String name) { this.id = id; this.name = name; } public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } } 2.1.2 定义原型工厂PrototypeFactory public class PrototypeFactory{ private static User prototypeUser; public static User setPrototypeUser(User prototypeUser){ prototypeUser = prototypeUser; } public static User getPrototypeUser(){ if(prototypeUser == null){ prototypeUser = new User("0","xxxx"); } return (User) prototypeUser.clone(); } } 2.1.3 使用 public static void main(String[] args) throws Exception{ PrototypeFactory.setPrototypeUser(new User("root","admin")); User prototypeUser1 = PrototypeFactory.getPrototypeUser(); User prototypeUser2 = PrototypeFactory.getPrototypeUser(); User prototypeUser3 = PrototypeFactory.getPrototypeUser(); }

除了clone,还可以使用反序列化和拷贝工具实现原型模式。

2.2 JDK源码——ArrayList public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ public Object clone() { try { ArrayList<?> v = (ArrayList<?>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } } }
三、其他设计模式

创建型模式 结构型模式

1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码

行为型模式

1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码4、设计模式——状态模式(State Pattern)5、设计模式——命令模式(Command Pattern)+ Spring相关源码6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码7、设计模式——备忘录模式(Memento Pattern)8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码
标签:

设计模式——原型模式(PrototypePattern)由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“设计模式——原型模式(PrototypePattern)