设计模式——Prototype模式

什么是Prototype模式

Prototype模式(原型模式)指的就是使用对象去制造新的对象,不像单例模式只制造出一个对象,原型模式制造的对象是多个的。原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。

实现Prototype模式

原型模式主要用于对象的复制,它的核心是就是类图中的原型类Prototype。Prototype类需要具备以下两个条件:

  • 实现Cloneable接口。在java语言有一个Cloneable接口,它的作用只有一个,就是在运行时通知虚拟机可以安全地在实现了此接口的类上使用clone方法。在java虚拟机中,只有实现了这个接口的类才可以被拷贝,否则在运行时会抛出CloneNotSupportedException异常。

  • 重写Object类中的clone方法。Java中,所有类的父类都是Object类,Object类中有一个clone方法,作用是返回对象的一个拷贝,但是其作用域protected类型的,一般的类无法调用,因此,Prototype类需要将clone方法的作用域修改为public类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public abstract class Shape implements Cloneable{


abstract void draw();

@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

public class Circle extends Shape {

@Override
void draw() {
System.out.println("this is Circle");
}
}

public class Rectangle extends Shape {

@Override
void draw() {
System.out.println("this is rectangle");
}
}


public class ShapeMap {
private Map<String, Shape> map = new HashMap<>();

public void register(String string, Shape shape){
map.put(string, shape);
}

public Shape get(String string) throws CloneNotSupportedException {
Shape shape = map.get(string);
//这里是核心我们获取到这个对象之后使用clone方法
return (Shape) shape.clone();
}
}

public class Main {

public static void main(String[] args) throws CloneNotSupportedException {
ShapeMap shapeMap = new ShapeMap();
Shape circle = new Circle();
Shape rectangle = new Rectangle();
shapeMap.register("circle", circle);
shapeMap.register("rectangle", rectangle);
Shape circleClone = shapeMap.get("circle");
Shape rectangleClone = shapeMap.get("rectangle");
circleClone.draw();
rectangleClone.draw();
}
}

最后输出打印

this is Circle

this is rectangle

-------------本文结束感谢阅读-------------