原型模式 使用场景 示例 java
时间: 2023-09-02 13:07:19 浏览: 40
原型模式的使用场景是在需要创建大量相似对象的情况下,可以通过复制一个已有对象的方法来创建新的对象,避免了重复创建相似对象的开销。
下面是一个使用原型模式的示例,假设我们有一个简单的图形类 Shape,其中包含一个颜色属性和一个绘制方法,我们需要创建大量不同颜色的图形对象:
```java
import java.util.HashMap;
import java.util.Map;
public abstract class Shape implements Cloneable {
private String color;
public Shape(String color) {
this.color = color;
}
public abstract void draw();
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
public class Circle extends Shape {
private int x;
private int y;
private int radius;
public Circle(String color, int x, int y, int radius) {
super(color);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing Circle - Color: " + getColor() + ", X: " + x + ", Y: " + y + ", Radius: " + radius);
}
}
public class Rectangle extends Shape {
private int x;
private int y;
private int width;
private int height;
public Rectangle(String color, int x, int y, int width, int height) {
super(color);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing Rectangle - Color: " + getColor() + ", X: " + x + ", Y: " + y + ", Width: " + width + ", Height: " + height);
}
}
public class ShapeCache {
private static Map<String, Shape> shapeMap = new HashMap<>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
public static void loadCache() {
Circle circle = new Circle("red", 10, 10, 20);
shapeMap.put("1", circle);
Rectangle rectangle = new Rectangle("blue", 5, 5, 10, 20);
shapeMap.put("2", rectangle);
}
}
public class Main {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape1 = ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape1.getType());
clonedShape1.draw();
Shape clonedShape2 = ShapeCache.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
clonedShape2.draw();
}
}
```
在上面的示例中,我们通过在 Shape 类中实现 Cloneable 接口,并重写 clone() 方法来实现原型模式。在 ShapeCache 类中,我们利用 HashMap 存储已有的图形对象,并通过 getShape() 方法来获取复制后的图形对象。最后在 Main 类中,我们通过 ShapeCache 类获取复制后的图形对象,并调用 draw() 方法绘制图形。