原型模式(Prototype Pattern)
是一种设计型模式。原型模式就是创建重复的对象,同时有能保证性能。
简单理解:就类似于细胞分裂,一个细胞分裂成两个一模一样的细胞。
原型模式和单例模式很像,单例模式是确保只存在一个实例,而原型模式是创建一模一样的对象。
创建一个Shape抽象类,它实现了Clonable()接口,Circle、Rectangle、Square都继承了Shape这个抽象类,再创建一个ShapeCache类,其中有一个用来存储Shape对象的Hashtable。ShapeCache类中有一个getShape()方法,接受一个String类型的id,如果这个id在Hashtable中存在,就返回Hashtable中获取的Shape对象的克隆。
package prototypePattern;
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 obj = null;
try {
obj = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return obj;
}
}
Circle类:
代表的是圆,继承了Shape这个抽象类。
package prototypePattern;
public class Circle extends Shape {
public Circle() {
type = "Circle";
}
@Override
void draw() {
System.out.println("圆形");
}
}
Rectangle类:
代表的是长方形,继承了Shape抽象类。
package prototypePattern;
public class Rectangle extends Shape {
public Rectangle() {
type = "Recentage";
}
@Override
void draw() {
System.out.println("长方形");
}
}
Square类:
代表的是正方形,继承了Shape抽象类。
package prototypePattern;
public class Square extends Shape {
public Square() {
type = "Square";
}
@Override
void draw() {
System.out.println("正方形");
}
}
ShapeCache类:
这个类中的方法体现了原型模式。
package prototypePattern;
import java.util.Hashtable;
public class ShapeCache {
//用来存储Shape的Hashtable
private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape shape = shapeMap.get(shapeId);
if(shape == null) {
return null;
}else {
//从Hashtable中取出Shape对象,返回其克隆对象
return (Shape) shape.clone();
}
}
public static void loadCache() {
Shape circle = new Circle();
circle.setId("1");
Rectangle rectangle = new Rectangle();
rectangle.setId("2");
Square square = new Square();
square.setId("3");
shapeMap.put(circle.getId(), circle);
shapeMap.put(rectangle.getId(), rectangle);
shapeMap.put(square.getId(), square);
}
}
测试类:
package prototypePattern;
import org.junit.Test;
public class TestJ {
@Test
public void test1() {
ShapeCache.loadCache();
Shape shape1 = ShapeCache.getShape("1");
Shape shape2 = ShapeCache.getShape("2");
Shape shape3 = ShapeCache.getShape("3");
Shape shape11 = ShapeCache.getShape("1");
shape1.draw();
// shape1和shape11都是克隆对象
System.out.println(shape1);
System.out.println(shape11);
System.out.println(shape1 == shape11);
}
}
运行结果:
圆形
prototypePattern.Circle@646be2c3
prototypePattern.Circle@797badd3
false
原型模式理解起来就是两个字:克隆。