原型模式的使用场景以及使用Java实现
时间: 2024-05-02 14:16:17 浏览: 9
原型模式适用于需要创建大量相似对象的场景,通过复制一个已有对象的实例来创建新的对象,避免了重复创建相似对象的开销。常见的应用场景包括:
1. 在初始化信息不发生变化的情况下,通过拷贝已有对象来提高创建对象的效率。
2. 通过改变值来创建一个新的对象,而不是从头开始构建一个新的对象。
3. 在多线程环境下,可以通过原型模式来避免竞争资源的情况。
以下是使用Java实现原型模式的示例代码:
```java
public abstract class Shape implements Cloneable { //抽象类Shape实现Cloneable接口
private String id;
protected String type;
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public abstract void draw();
public Object clone() { //实现clone方法
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
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) cachedShape.clone(); //返回克隆的对象
}
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Rectangle rectangle = new Rectangle();
rectangle.setId("2");
shapeMap.put(rectangle.getId(), rectangle);
}
}
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,Rectangle和Circle继承自Shape,并实现了clone方法。ShapeCache类中使用Hashtable来存储已有的对象,通过getShape方法获取已有对象并进行克隆,避免了重复创建相似对象的开销。在main方法中,我们从ShapeCache中获取已有对象并进行克隆,输出克隆对象的类型。