设计模式-工厂模式

设计模式-工厂模式

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

参考

工厂模式是最常用的设计模式之一。这种类型的设计模式属于创建型模式,它它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

使用场景

工厂模式一般用于对于不同的场景,需要创建不同的对象,但是这些对象实现的功能是很相似的,可以抽象出一个父类实现对应对象的创建。

  • 在加载配置文件时,通过后缀来解析配置文件,并将文件内容写入内存。

Demo分析

工厂模式的 UML 图

分析:

根据上图逻辑,我们有一个Shape的抽象类,同时有对应的三个子类。我们可以通过ShapeFactory来创建对应的实例。

Python实现

class Shape():
  """
    ## 形状的抽象类
  """
  def __init__(self, shapeName):
    self.shapeName = shapeName
  def draw(self):
    print("drawing " + self.shapeName)

class Circle(Shape):
  def __init__(self, shapeName, radius):
    super().__init__(shapeName)
    self.radius = radius

class Square(Shape):
  def __init__(self, shapeName, xWidth):
    super().__init__(shapeName)
    self.xWidth = xWidth

class Rectangle(Shape):
  def __init__(self, shapeName, xWidth, yHeight):
    super().__init__(shapeName)
    self.xWidth = xWidth
    self.yHeight = yHeight

class ShapeFactory():
  """
    ## 工厂模式实现
  """
  shapeConfig = {
    "circle": Circle,
    "square": Square,
    "rectangle": Rectangle
  }
  @classmethod
  def getShape(self, shapeName, *args, **kwargs):
    obj = self.shapeConfig.get(shapeName, None)
    if obj is None:
      raise Exception("Shape not found")
    return obj(shapeName, *args, **kwargs)

def test():
  circle = ShapeFactory().getShape("circle", 10)
  square = ShapeFactory().getShape("square", 10)
  circle.draw()
  square.draw()

if __name__ == '__main__':
  test()

输出

drawing circle
drawing square

Go实现

package main

import "fmt"

type ShapeDrawer interface {
	Draw()
}

type shapeCommFuncs struct {
	Name string
}

type Circle struct {
	x, y, radius int
	shapeCommFuncs
}

func (t *shapeCommFuncs) Draw() {
	fmt.Printf("绘制%s\n", t.Name)
}

type Square struct {
	x, y, length int
	shapeCommFuncs
}

type Rectangle struct {
	x, y, width, height int
	shapeCommFuncs
}

/**
 * 工厂模式创建对象
 */
func createFactory(shapeName string) ShapeDrawer {
	switch shapeName {
	case "Circle":
		return &Circle{
			shapeCommFuncs: shapeCommFuncs{Name: shapeName},
		}
	case "Square":
		return &Square{
			shapeCommFuncs: shapeCommFuncs{Name: shapeName},
		}
	case "Rectangle":
		return &Rectangle{
			shapeCommFuncs: shapeCommFuncs{Name: shapeName},
		}
	default:
		return nil
	}
}

func test() {
	c := createFactory("Circle")
	s := createFactory("Square")
	c.Draw()
	s.Draw()
}

func main() {
	test()
}

输出

绘制Circle
绘制Square

总结

工厂模式提高了代码的灵活性,例如我们自己开发了绘制圆形的一个类并且公布在网上。当其他的协作者加入时,可以很方便的向模块中添加新的绘制方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值