原型模式
1、原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。
2、例子
原型模式就好比细胞分裂和克隆,完完全全再生成一个一模一样的物品。 比如JAVA 中的 Object clone() 方法。目前在实际项目中,原型模式很少单独出现,一般是和工厂方法模式一起出现,通过 clone 的方法创建一个对象,然后由工厂方法提供给调用者。原型模式已经与 Java 融为浑然一体,大家可以随手拿来使用。
3、原型模式的优缺点
优点: 1、性能提高。 2、逃避构造函数的约束。
缺点: 1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。 2、必须实现 Cloneable 接口。
4、代码
public class EntryptTest {
public static void main(String[] args) throws Exception {
ShapeCache.createShape();
Shape square = ShapeCache.getShape("square");
System.out.println("square :" + square.type);
Shape circle = ShapeCache.getShape("circle");
System.out.println("circle :" + circle.type);
Shape rectangle = ShapeCache.getShape("rectangle");
System.out.println("rectangle :" + rectangle.type);
}
}
//创建一个抽象类,实现Cloneable 接口,重写clone方法
abstract class Shape implements Cloneable {
private String id;
protected String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
protected Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
//然后实体类扩展抽象类
class Rectangle extends Shape {
public Rectangle() {
type = "Rectangle";
}
}
class Circle extends Shape {
public Circle() {
type = "Circle";
}
}
class Square extends Shape {
public Square() {
type = "Square";
}
}
//创建一个生成对象的类,并存储该类。
class ShapeCache {
private static Map<String, Shape> shapeMap = new HashMap<>();
//输入相应的shapeId会得到
public static Shape getShape(String shapeId) {
Shape shapeCache = shapeMap.get(shapeId);
return (Shape) shapeCache.clone();
}
//创建形状并且添加到hashMap中,一般这里都是比较复杂的生成操作
public static void createShape() {
Circle circle = new Circle();
circle.setId("circle");
shapeMap.put(circle.getId(), circle);
Square square = new Square();
square.setId("square");
shapeMap.put(square.getId(), square);
Rectangle rectangle = new Rectangle();
rectangle.setId("rectangle");
shapeMap.put(rectangle.getId(), rectangle);
}
}
运行结果:
square :Square
circle :Circle
rectangle :Rectangle
分析:
我们将创建一个抽象类 Shape 和扩展了 Shape 类的实体类。下一步是定义类 ShapeCache,该类把 shape 对象存储在一个 Hashtable 中,并在请求的时候返回它们的克隆。
main方法中我们的演示类使用 ShapeCache 类来获取 Shape 对象。
同时在补充一下浅拷贝和深拷贝。
浅拷贝:
被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。即对象的浅拷贝会对“主”对象进行拷贝,但不会复制主对象里面的对象。”里面的对象“会在原来的对象和它的副本之间共享。
简而言之,浅拷贝仅仅复制所考虑的对象,而不复制它所引用的对象。
深拷贝:
深拷贝是一个整个独立的对象拷贝,深拷贝会拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生深拷贝。深拷贝相比于浅拷贝速度较慢并且花销较大。
简而言之,深拷贝把要复制的对象所引用的对象都复制了一遍。