原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
UML图

1.创建实现了Clonable的抽象类
public abstract class Shape implements Clonable{
private String id;
protected Stirng 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;
}
}
2.扩展了上面抽象类的实体类
public class Rectangle extends Shape{
public Rectangle(){
type = "Retangle";
}
@Override
public void draw(){
System.out.println("Inside Rectangle :draw() method.");
}
}
public class Square extends Shape{
public Square(){
type="Squre";
}
@Override
public void draw(){
System.out.println("Inside Square :draw() method");
}
}
public class Circle extends Shape{
public Circle(){
type="Circle";
}
@Override
public void draw(){
System.out.println("Inside Circle :draw() method");
}
}
3.创建一个类,从数据库中获取实体类,并把他们存储在一个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)cacheShape.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);
}
}
4.运行
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());
}
}
本文详细介绍了原型模式的概念及其在Java中的实现。通过一个具体的例子展示了如何使用原型模式来创建对象副本,以此达到提高性能的目的。文章涵盖了抽象类的定义、具体实体类的实现,以及缓存加载的过程。

被折叠的 条评论
为什么被折叠?



