当前位置: 首页> 科技> 数码 > 原型模式(Prototype Pattern)

原型模式(Prototype Pattern)

时间:2025/7/13 3:54:18来源:https://blog.csdn.net/weixin_43298211/article/details/142289673 浏览次数:2次

原型模式是一种创建型设计模式,使用克隆方法来复制现有对象,从而避免重复的初始化操作,特别适用于创建重复对象的场景。

适用场景:

  • 当一个系统需要创建新对象的对象系统中,可通过克隆一个原型并对其进行改造。
  • 当对象的创建成本比较大(如复杂的初始化)时。

示例代码:

abstract class Shape implements Cloneable {abstract void draw();@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}class Circle extends Shape {@Overridevoid draw() {System.out.println("Drawing a Circle");}
}class PrototypeManager {private Map<String, Shape> prototypes = new HashMap<>();public PrototypeManager() {prototypes.put("circle", new Circle());// 可以添加更多类型}public Shape getShape(String type) throws CloneNotSupportedException {return (Shape) prototypes.get(type).clone();}
}public class Client {public static void main(String[] args) throws CloneNotSupportedException {PrototypeManager pm = new PrototypeManager();Shape shape = pm.getShape("circle");shape.draw(); // 输出: Drawing a Circle}
}

关键字:原型模式(Prototype Pattern)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: