内容简介
第三个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模式与常规不同的是,它不是直接对一个类进行实例化创造新的对象,而是通过拷贝已存在的对象来复制出新的对象
总结
暂时不会有新的读书笔记了,要上网课了,先观望观望