java设计模式读书笔记[3]——Prototype模式
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java设计模式读书笔记[3]——Prototype模式,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2793字,纯文字阅读大概需要4分钟。
内容图文
内容简介
第三个Java设计模式Prototype模式,我们通常使用new关键字指定类名来生成类的实例,但是我们有时也会遇到“在不指定类名的前提下生成实例”的需求。这时候我们通过Prototype模式,就能利用clone方法的Cloneable接口的使用来创建出实例的副本。
实现
首先先要创造一个具有clone方法的抽象类以方便我们进行复制
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";
}
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square extends Shape {
public Square(){
type = "Square";
}
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
接下来是创建一个新的类,作为这几个实体类的载体,并将其全部存在Hashtable中
package test;
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();
}
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());
}
}
输出结果:
Shape : Circle
Shape : Square
Shape : Rectangle
优缺点介绍
- 优点
(1)提高了运行时的性能,提出了不使用new创建新实例的模式
(2)避开了构造函数的约束性 - 缺点
(1)必须实现clone方法才能进行
(2)复制过程格式单一,变通性不是特别好
注意事项
Prototype模式与常规不同的是,它不是直接对一个类进行实例化创造新的对象,而是通过拷贝已存在的对象来复制出新的对象
总结
暂时不会有新的读书笔记了,要上网课了,先观望观望
PleasedSheep 发布了8 篇原创文章 · 获赞 2 · 访问量 123 私信 关注内容总结
以上是互联网集市为您收集整理的java设计模式读书笔记[3]——Prototype模式全部内容,希望文章能够帮你解决java设计模式读书笔记[3]——Prototype模式所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。