• 设计模式-原型模式


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

            以下是一个简单的 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 方法获取,这个方法会返回一个克隆的对象,而不是创建一个新的对象。

  • 相关阅读:
    linux-文件服务
    STK12与Python联合仿真(一):环境搭建
    5个月做视频号的心路历程
    学网安兴趣最重要
    【AI视野·今日CV 计算机视觉论文速览 第262期】Fri, 6 Oct 2023
    解决WSL2占用内存过多问题(Docker on WSL2: VmmemWSL)
    《多线程案例》阻塞队列、定时器、线程池、饿汉与懒汉模式
    Mysql和Oracle的语法区别?
    iPhone垃圾清理器:AnyMP4 iOS Cleaner for mac
    C++广搜例题代码加讲解(1)
  • 原文地址:https://blog.csdn.net/m0_65014849/article/details/133905353