• 设计模式-原型模式


            原型模式是一种创建型设计模式,它用于创建重复的对象,同时又能保证性能。这种类型的设计模式是基于一个原型实例,通过复制(克隆)自身来创建新的对象。

            以下是一个简单的 Java 版本的原型模式的示例:

    1. public abstract class Shape implements Cloneable {
    2. private String id;
    3. protected String type;
    4. abstract void draw();
    5. public String getType(){
    6. return type;
    7. }
    8. public String getId() {
    9. return id;
    10. }
    11. public void setId(String id) {
    12. this.id = id;
    13. }
    14. public Object clone() {
    15. Object clone = null;
    16. try {
    17. clone = super.clone();
    18. } catch (CloneNotSupportedException e) {
    19. e.printStackTrace();
    20. }
    21. return clone;
    22. }
    23. }
    24. public class Rectangle extends Shape {
    25. public Rectangle(){
    26. type = "Rectangle";
    27. }
    28. @Override
    29. public void draw() {
    30. System.out.println("Inside Rectangle::draw() method.");
    31. }
    32. }
    33. public class Square extends Shape {
    34. public Square(){
    35. type = "Square";
    36. }
    37. @Override
    38. public void draw() {
    39. System.out.println("Inside Square::draw() method.");
    40. }
    41. }
    42. public class ShapeCache {
    43. private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
    44. public static Shape getShape(String shapeId) {
    45. Shape cachedShape = shapeMap.get(shapeId);
    46. return (Shape) cachedShape.clone();
    47. }
    48. public static void loadCache() {
    49. Rectangle rectangle = new Rectangle();
    50. rectangle.setId("1");
    51. shapeMap.put(rectangle.getId(), rectangle);
    52. Square square = new Square();
    53. square.setId("2");
    54. shapeMap.put(square.getId(), square);
    55. }
    56. }
    57. public class PrototypePatternDemo {
    58. public static void main(String[] args) {
    59. ShapeCache.loadCache();
    60. Shape clonedShape = (Shape) ShapeCache.getShape("1");
    61. System.out.println("Shape : " + clonedShape.getType());
    62. Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
    63. System.out.println("Shape : " + clonedShape2.getType());
    64. }
    65. }


            在这个示例中,Shape 是一个实现了 Cloneable 接口的抽象类,Rectangle 和 Square 是 Shape 的具体子类。ShapeCache 类负责存储和克隆原型对象。当需要一个新的 Shape 对象时,可以通过 ShapeCache.getShape 方法获取,这个方法会返回一个克隆的对象,而不是创建一个新的对象。

  • 相关阅读:
    手写分布式配置中心(二)实现分布式配置中心的简单版本
    Centos - SSH 服务搭建
    助力财务管理转型升级——宁夏烟草智能财务共享中心建设
    【JUC系列-15】深入理解CompletableFuture的基本使用
    C++(四)
    Java多线程核心工具类
    Lucene全文检索
    使用 Lhotse 高效管理音频数据集
    数据结构——时间复杂度
    java毕业设计“传情旧物”网站(附源码、数据库)
  • 原文地址:https://blog.csdn.net/m0_65014849/article/details/133905353