1.基本概念
1)客户(Client)角色:客户类提出创建对象的请求。
2)抽象原型(Prototype)角色:这是一个抽象角色,通常由一个Java接口或Java抽象类实现。此角色给出所有的具体原型类所需的接口。
3)具体原型(Concrete Prototype)角色:被复制的对象。此角色需要实现抽象的原型角色所要求的接口。
1)简单模式
2)登记模式
2.代码(登记模式)
package com.chengjie; import java.util.HashMap; 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; } } class Rectangle extends Shape { public Rectangle() { type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } class Square extends Shape { public Square() { type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } } class Circle extends Shape { public Circle() { type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } class ShapeCache { private static HashMap<String, Shape> shapeMap = new HashMap<String, Shape>(); public static Shape getShape(String id) { Shape shape = shapeMap.get(id); return (Shape) shape.clone(); } public static void fill() { 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); } } public class TestPrototype { public static void main(String[] args) { ShapeCache.fill(); Shape cloneShape = ShapeCache.getShape("1"); System.out.println("Shape:" + cloneShape.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()); } }
3.优点
4.缺点
5.使用场景
6.参考
http://www.runoob.com/design-pattern/prototype-pattern.html
https://www.cnblogs.com/java-my-life/archive/2012/04/11/2439387.html
原文:https://www.cnblogs.com/forTheDream1991/p/10483192.html