原型模式

来源:互联网 发布:死侍蜘蛛侠 知乎 编辑:程序博客网 时间:2024/04/29 22:05

原型模式

一、原型模式(Prototype Pattern)
利用已有的对象复制出新的对象从而快速的创建新的对象,减少复杂对象创建的复杂过程。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
JAVA主要通过实现一个Cloneable接口,重写Object的clone方法。
为了快速的做这个封装了一个抽象类(基类)
package com.grd.prototypepattern;import java.security.KeyStore.PrivateKeyEntry;public abstract class Shape implements Cloneable{private String id;protected String type;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getType() {return type;}public abstract void draw();@Overrideprotected Object clone() throws CloneNotSupportedException {// TODO Auto-generated method stubShape shape = null;try{shape = (Shape) super.clone();}catch (Exception e) {// TODO: handle exception}return shape;}}
下方分别实现不同的具体类
public class Circle extends Shape{public Circle() {type = "Circle";}@Overridepublic void draw() {// TODO Auto-generated method stubSystem.out.println("draw inside circle");}}
package com.grd.prototypepattern;public class Square extends Shape{public Square() {type = "Square";}@Overridepublic void draw() {System.out.println("inside square draw");}}

有一个缓存具体对象的类,这个类的实例持有上方的两个类的实例,这两个被持有的实例就是原型
package com.grd.prototypepattern;import java.util.HashMap;public class ShapeCache {HashMap<String, Shape> shapCache = new HashMap<String,Shape>();public Shape getShape(String id){Shape shape =  shapCache.get(id);if (shape!=null) {try {return (Shape) shape.clone();} catch (CloneNotSupportedException e) {return null;}}else {return null;}}public void loadCache(){Circle circle = new Circle();circle.setId("1");shapCache.put(circle.getId(), circle);System.out.println(circle.toString());Square square = new Square();square.setId("2");shapCache.put(square.getId(), square);System.out.println(square.toString());}}

在demo类里获取实例
package com.grd.prototypepattern;public class PrototypePatternDemo {public static void main(String[] args){ShapeCache shapeCache  = new ShapeCache();shapeCache.loadCache();Shape circle = shapeCache.getShape("1");circle.draw();System.out.println(circle.toString());Shape square = shapeCache.getShape("2");square.draw();System.out.println(square.toString());}}

运行结果如下

com.grd.prototypepattern.Circle@7852e922

com.grd.prototypepattern.Square@4e25154f

draw inside circle

com.grd.prototypepattern.Circle@70dea4e

inside square draw

com.grd.prototypepattern.Square@5c647e05

每一个对象的都不一样,这里进行了浅拷贝,还有深拷贝。
这里对于浅拷贝说一下,在新建的对象里所有的非基本类型会拷贝引用,不会创建新的实例。
深拷贝是指在其内拥有的的对象再次进行clone()方法创建新的并且把引用重新指向新的对象。


原创粉丝点击