设计模式-原型模式

设计模式-原型模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(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()
}

输出

Shape rectangle
Shape square

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()

输出

Circle with radius 3
Square with side 4

小结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值