一 设计模式创建型模式( 九 )


注意事项:与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的 。浅拷贝实现 ,重写,深拷贝是通过实现读取二进制流 。
实现
我们将创建一个抽象类Shape和扩展了Shape类的实体类 。下一步是定义类,该类把 shape 对象存储在一个中,并在请求的时候返回它们的克隆 。
,我们的演示类使用类来获取Shape对象 。
步骤 1
创建一个实现了接口的抽象类 。
public abstract class Shape implements Cloneable {private String id;protected String type;abstract void draw();public String getType(){return type;}public String getId() {return id;}public void setId(String id) {this.id = id;}public Object clone() {Object clone = null;try {clone = super.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return clone;}}
步骤 2
创建扩展了上面抽象类的实体类 。
public class Rectangle extends Shape {public Rectangle(){type = "Rectangle";}@Overridepublic void draw() {System.out.println("Inside Rectangle::draw() method.");}}
public class Square extends Shape {public Square(){type = "Square";}@Overridepublic void draw() {System.out.println("Inside Square::draw() method.");}}
public class Circle extends Shape {public Circle(){type = "Circle";}@Overridepublic void draw() {System.out.println("Inside Circle::draw() method.");}}
步骤 3
创建一个类,从数据库获取实体类,并把它们存储在一个中 。
import java.util.Hashtable;public class ShapeCache {private static Hashtable shapeMap = new Hashtable();public static Shape getShape(String shapeId) {Shape cachedShape = shapeMap.get(shapeId);return (Shape) cachedShape.clone();}// 对每种形状都运行数据库查询,并创建该形状// shapeMap.put(shapeKey, shape);// 例如,我们要添加三种形状public static void loadCache() {Circle circle = new Circle();circle.setId("1");shapeMap.put(circle.getId(),circle);Square square = new Square();square.setId("2");shapeMap.put(square.getId(),square);Rectangle rectangle = new Rectangle();rectangle.setId("3");shapeMap.put(rectangle.getId(),rectangle);}}
步骤 4
使用类来获取存储在中的形状的克隆 。
public class PrototypePatternDemo {public static void main(String[] args) {ShapeCache.loadCache();Shape clonedShape = (Shape) ShapeCache.getShape("1");System.out.println("Shape : " + clonedShape.getType());Shape clonedShape2 = (Shape) ShapeCache.getShape("2");System.out.println("Shape : " + clonedShape2.getType());Shape clonedShape3 = (Shape) ShapeCache.getShape("3");System.out.println("Shape : " + clonedShape3.getType());}}
步骤 5
执行程序,输出结果:
Shape : CircleShape : SquareShape : Rectangle