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

什么是生成器设计模式

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

猜你喜欢

转载自blog.csdn.net/wujiesunlirong/article/details/135865363