• 设计模式-原型模式


    设计模式-原型模式

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V8Omd1bH-1660615038349)(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT-doc3ZTYZ4RhCEg4hFJf6TOpzPCbhDyhIbQ&usqp=CAU)]

    参考


    原型模式是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

    这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。

    使用场景

    • 类初始化需要消化非常多的资源、硬件资源等。
    • 一个对象多个修改者的场景

    Demo分析

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MDSyRZtk-1660615038350)(C:\Users\86136\AppData\Roaming\Typora\typora-user-images\image-20220816090348978.png)]

    分析:

    我们将创建一个抽象类Shape和扩展了Shape类的实体类。下一步是定义类ShapeCache,该类把shape对象存储在一个Hashtable中,并在请求的时候返回它们的克隆。

    Go实现

    package main
    
    import "fmt"
    
    /**
     * 抽象类接口
     */
    type Shape struct {
    	Id   string
    	Type string
    }
    
    func (s *Shape) getType() string {
    	return s.Type
    }
    
    func (s *Shape) getId() string {
    	return s.Id
    }
    
    type ShapeT interface {
    	Draw()
    	Clone() ShapeT
    }
    
    type Rectangle struct {
    	Shape
    }
    
    type Square struct {
    	Shape
    }
    
    func (s *Square) Draw() {
    	fmt.Printf("Drawing a square with id %s\n", s.getId())
    }
    
    /**
     * 深拷贝,核心
     */
    func (s *Square) Clone() ShapeT {
    	return &Square{Shape{
    		Id:   s.Id,
    		Type: s.Type,
    	}}
    }
    
    func (r *Rectangle) Draw() {
    	fmt.Printf("Drawing a rectangle with id %s\n", r.getId())
    }
    
    /**
     * 深拷贝,核心
     */
    func (r *Rectangle) Clone() ShapeT {
    	return &Rectangle{Shape{
    		Id:   r.Id,
    		Type: r.Type,
    	}}
    }
    
    type ShapeCache struct {
    	shapes map[string]ShapeT
    }
    
    func (s *ShapeCache) loadCache() {
    	s.shapes = make(map[string]ShapeT)
    	s.shapes["1"] = &Rectangle{
    		Shape{
    			Id:   "1",
    			Type: "rectangle",
    		},
    	}
    	s.shapes["2"] = &Square{
    		Shape{
    			Id:   "2",
    			Type: "square",
    		},
    	}
    }
    
    func (s *ShapeCache) getShape(id string) ShapeT {
    	return s.shapes[id].Clone()
    }
    
    func test() {
    	shapeCache := ShapeCache{}
    	shapeCache.loadCache()
    	rect := shapeCache.getShape("1").(*Rectangle)
    	fmt.Printf("Shape %s\n", rect.getType())
    	square := shapeCache.getShape("2").(*Square)
    	fmt.Printf("Shape %s\n", square.getType())
    }
    
    func main() {
    	test()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97

    输出

    Shape rectangle
    Shape square
    
    • 1
    • 2

    Python实现

    class Shape(object):
      def __init__(self, Id, type):
        self.id = Id
        self.type = type
      def getId(self):
        return self.id
      def getType(self):
        return self.type
      def clone(self):
        """
          ## 原型模式的关键在于clone方法
        """
        return super(Shape, self).clone()
    
    class Circle(Shape):
      def __init__(self, Id, type, radius):
        super(Circle, self).__init__(Id, type)
        self.radius = radius
      def draw(self):
        print("Circle with radius %d" % self.radius)
    
    class Square(Shape):
      def __init__(self, Id, type, side):
        super(Square, self).__init__(Id, type)
        self.side = side
      def draw(self):
        print("Square with side %d" % self.side)
    
    class ShapeCache(object):
      def __init__(self):
        self.shapeMap = {}
      def getShape(self, Id):
        shape = self.shapeMap.get(Id, None)
        if shape == None:
          raise Exception("Shape not found")
        return shape
      def loadCache(self):
        circle = Circle("1", "Circle", 3)
        square = Square("2", "Square", 4)
        self.shapeMap["1"] = circle
        self.shapeMap["2"] = square
    
    def PrototypePatternDemo():
      shapeCache = ShapeCache()
      shapeCache.loadCache()
      circle = shapeCache.getShape("1")
      circle.draw()
      square = shapeCache.getShape("2")
      square.draw()
    
    if __name__ == '__main__':
      PrototypePatternDemo()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    输出

    Circle with radius 3
    Square with side 4
    
    • 1
    • 2

    小结

    原型模式就是利用对已有对象进行复制的方式,来创建对象,以达到节省创建时间的目的。

  • 相关阅读:
    说说考研调剂都有哪些具体要求?
    请问上传失败原因以及调整方法
    人工智能轨道交通行业周刊-第59期(2023.9.4-9.10)
    Ubuntu 14.04:安装 PaddleOCR 2.3
    【单目标优化求解】粒子群混沌混合蝴蝶优化算法求解最优目标问题(HPSOBOA)【含Matlab源码 1538期】
    21天学习挑战:经典算法---冒泡排序
    HarmonyOS应用侧与前端页面数据通道建立
    【Django框架】——24 Django视图 06 状态保持Cookie
    (数组 / 字符串) 55. 跳跃游戏 ——【Leetcode每日一题】
    Java链接redis集群
  • 原文地址:https://blog.csdn.net/qq_52785898/article/details/126359928