原型模式是一种创建型设计模式,它允许通过复制现有对象来创建新对象,甚至是复杂对象,而又无需使代码依赖它们所属的类。
Shape:抽象原型类,声明具备clone能力,抽象原型类的作用是规范化克隆方法的使用,确保每个具体的原型类都有克隆方法,并且在运行时可以通过该方法来动态地创建新对象,例如java中的Cloneable接口
Rectangle/Circle:具体原型类,他实现抽象类中声明的克隆方法,在克隆方法中返回自己的克隆对象
代码示例:
抽象原型类:Shape
@Data
public abstract class Shape implements Cloneable {
private String type;
@Override
public Shape clone() {
Shape clone = null;
try {
clone = (Shape) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
具体原型类:Rectangle
@Data
public class Rectangle extends Shape {
private int length;
private int width;
public Rectangle(int length,int width) {
this.length = length;
this.width = width;
setType("Rectangle");
}
}
具体原型类:Circle
@Data
public class Circle extends Shape {
private int radius;
public Circle(int radius) {
this.radius = radius;
setType("Circle");
}
}
运行示例:
public static void main(String[] args) {
Shape rectangle = new Rectangle(10,5);
Shape rectangleClone = rectangle.clone();
System.out.println(rectangle);
System.out.println(rectangleClone);
Shape circle = new Circle(10);
Shape circleClone = circle.clone();
System.out.println(circle);
System.out.println(circleClone);
}
在这个示例中,Shape 是原型接口,它实现了Cloneable接口,此处clone方法可以改成任意的名称,因为Cloneable接口是个空接口,你可以任意定义实现类的方法名,如cloneA或者cloneB,因为此处的重点是super.clone()这句话,super.clone()调用的是Object的clone()方法。
Rectangle 和 Circle 是具体的原型类。
优点:
- 减少对象的创建时间:避免了重复的初始化操作,直接通过复制现有对象进行创建,提高了对象创建的效率。
- 简化对象创建过程:不需要关注对象的具体创建过程,只需克隆一个现有对象即可。
缺点:
- 深克隆问题:如果对象中含有引用类型的成员变量,需要实现深克隆才能保证克隆对象和原对象的引用类型不相互影响。
适用场景:
当需要创建一个对象,但创建过程复杂或者依赖于现有对象时,可以考虑使用原型模式。