原型模式
来源:互联网 发布:百度推广搜索合作网络 编辑:程序博客网 时间:2024/05/16 01:21
就是实例克隆。利用已有的原型对象,快速的生成原型对象一样的实例。
创建一个实现Clonable 接口的抽象类:
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; }}
抽象类的实现类:
public class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); }}public class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); }}public class Circle extends Shape { public Circle(){ type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); }}
//出去实体类,存入hashmap 中
import java.util.Hashtable;public class ShapeCache { private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); 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); }}
测试:
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()); }}
阅读全文
0 0
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型 模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- 原型模式
- mysql索引
- springboot scheduled 异步执行
- 设计模式
- Object Detection论文笔记(2)
- 设置session验证码有效时间,定时删除session中的验证码
- 原型模式
- 数据库双机热备份
- 免费和开源的动图gif工具,没广告!效率高,体积小,精通18国语言,必备良品!!!
- 获取微信公众平台的用户openid
- 【bzoj1717】[Usaco2006 Dec]Milk Patterns 产奶的模式
- pomelo(五) Tutorial 2 Treasures
- WordPress主题开发: 制作文章页面single.php
- 《算法导论》个人笔记(序言)
- <meta>中的shrink-to-fit=no