原型模式是创建模式中的一个。
原型模式有助于创建重复对象具有更好的性能。
在原型模式的现有对象的副本返回,而不是创造新的。
我们使用原型设计模式,如果创建新对象的成本是昂贵的和资源密集的。
下面的代码演示了如何使用原型模式来创建对象。
首先,它创建一个实现了Cloneable接口形状抽象类。
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 clone() {
clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
然后,它会创建扩展Shape类的三个具体的类。
class Rectangle extends Shape {
public Rectangle(){
type = \"Rectangle\";
}
@Override
public void draw() {
System.out.println(\"Inside Rectangle::draw() method.\");
}
}
class Square extends Shape {
public Square(){
type = \"Square\";
}
@Override
public void draw() {
System.out.println(\"Inside Square::draw() method.\");
}
}
class Circle extends Shape {
public Circle(){
type = \"Circle\";
}
@Override
public void draw() {
System.out.println(\"Inside Circle::draw() method.\");
}
}
然后创建了一个ShapeProtoType类并返回形状的原型。
class ShapeProtoType{
//from w w w . jav a 2 s. c o m
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);
Square square = new Square();
square.setId(\"2\");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId(\"3\");
shapeMap.put(rectangle.getId(),rectangle);
}
}
public class Main{
public static void main(String[] args) {
ShapeProtoType.loadCache();
Shape clonedShape = (Shape) ShapeProtoType.getShape(\"1\");
System.out.println(\"Shape : \" + clonedShape.getType());
Shape clonedShape2 = (Shape) ShapeProtoType.getShape(\"2\");
System.out.println(\"Shape : \" + clonedShape2.getType());
Shape clonedShape3 = (Shape) ShapeProtoType.getShape(\"3\");
System.out.println(\"Shape : \" + clonedShape3.getType());
}
}
继续阅读与本文标签相同的文章
上一篇 :
图解优秀软件设计人员的8个习惯
下一篇 :
当我们说某项技术已死,我们在说什么
-
PS保存图片提示“无法完成请求”,这里有4种解决方法!
2026-05-14栏目: 教程
-
想买1000元左右的5G手机?我们需要等多久?
2026-05-14栏目: 教程
-
剧情反转?美企主动购买华为5G技术,华为成赞赏排行榜第一名!
2026-05-14栏目: 教程
-
城市数字化后,新一代内生安全系统可全方位保护
2026-05-14栏目: 教程
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
