设计模式-生成器设计模式

什么是生成器设计模式

  1. 众所周知我们设计代码的时候要将代码设计出模块化的,一个功能是一个模块,那么生成器设计模式,是将一个类再度进行了一个拆分,让一个类的内部进行了单一职责化,其实我们在平时开发的时候就会不经意的使用到该设计模式。
  2. 相当于在N个相似的生产线上我们通过定义了一个共有的interface,这N个生成线都是以相似的步骤来生成东西。
  3. 该模式有点类似与工厂设计模式,工厂设计模式是用来生成一系列相关的对象,生成器设计模式可以将一个复杂的对象拆分成很多步骤来完成。

使用场景

  1. 复杂对象的创建:当对象的创建过程涉及到多个步骤,并且这些步骤的顺序可能会变化时,生成器模式可以提供一种灵活的方式来创建对象。

  2. 不同的表示:当一个对象可以有多种不同的表示,而且你希望在运行时动态地选择表示时,生成器模式可以提供一种解决方案。

  3. 封装创建过程:当你希望封装对象的创建过程,以便在不暴露对象的内部表示的情况下创建对象时,生成器模式可以提供帮助。

UML图

在这里插入图片描述

代码

package generator

type Generator interface {
   
	setWindow()
	setDoor()
	setWall()
	setRoof()
}

type GeneratorHouse struct {
   
}

func NewGeneratorHouse() *GeneratorHouse {
   
	return &GeneratorHouse{
   }
}

func (g *GeneratorHouse) setWindow() {
   
	println("set window for house")
}

func (g *GeneratorHouse) setDoor() {
   
	println("set door for house")
}

func (g *GeneratorHouse) setWall() {
   
	println("set wall for house")
}

func (g *GeneratorHouse) setRoof() {
   
	println("set roof for house")
}
func (g *GeneratorHouse) GetResult() {
   
	println("set window for highrises")
}

type GeneratorHighRises struct {
   
}

func (g *GeneratorHighRises) setWindow() {
   
	println("set window for highrises")
}

func (g *GeneratorHighRises) setDoor() {
   
	println("set door for highrises")
}

func (g *GeneratorHighRises) setWall() {
   
	println("set wall for highrises")
}

func (g *GeneratorHighRises) setRoof() {
   
	println("set roof for highrises")
}

func (g *GeneratorHighRises) GetResult() {
   
	println("set window for highrises")
}

type Director struct {
   
}

func (d *Director) Excuter(task string) {
   
	if task == "house" {
   
		house := NewGeneratorHouse()
		house.setDoor()
		house.setRoof()
		house.setWall()
		house.setWindow()
		house.GetResult()
	}
	if task == "highrises" {
   
		highrises := &GeneratorHighRises{
   }
		highrises.setDoor()
		highrises.setRoof()
		highrises.setWall()
		highrises.setWindow()
		highrises.GetResult()
	}
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-27 18:32:03       75 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-27 18:32:03       80 阅读
  3. 在Django里面运行非项目文件

    2024-01-27 18:32:03       64 阅读
  4. Python语言-面向对象

    2024-01-27 18:32:03       75 阅读

热门阅读

  1. 独孤思维:绝版书一个月赚了1万

    2024-01-27 18:32:03       55 阅读
  2. SVG 字体 – SVG text (11)

    2024-01-27 18:32:03       47 阅读
  3. go中context的使用场景

    2024-01-27 18:32:03       47 阅读
  4. 【无标题】OpenAi

    2024-01-27 18:32:03       46 阅读
  5. Docker 的基本概念和优势

    2024-01-27 18:32:03       57 阅读
  6. 第六章(原理篇) 微前端间的通信机制

    2024-01-27 18:32:03       55 阅读
  7. TCP三次握手-普通话版

    2024-01-27 18:32:03       41 阅读
  8. 处理器架构

    2024-01-27 18:32:03       51 阅读
  9. mysql5.7.19安装步骤

    2024-01-27 18:32:03       54 阅读