Golang中的设计模式 (二)--创造型设计模式

Golang中的设计模式 (二)–创造型设计模式

建造者模式

建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。

汽车由很多组建构成,下面用一个汽车的构建事例讲解建造者模式
golang代码事例:

package main

import "fmt"

// Car 产品角色(汽车)
type Car struct {
	Brand string
	Type  string
	Color string
}

// Drive 骑乘显示
func (this *Car) Drive() error {
	fmt.Printf("A %s %s %s car is running on the road!\n", this.Color, this.Type, this.Brand)
	return nil
}

// Builder 建造者角色
type Builder interface {
	PaintColor(color string) Builder
	AddBrand(brand string) Builder
	SetType(t string) Builder
	Build() Car
}

// ConcreteBuilder 具体的建造者
type ConcreteBuilder struct {
	ACar Car
}

func (this *ConcreteBuilder) PaintColor(cor string) Builder {
	this.ACar.Color = cor
	return this
}

func (this *ConcreteBuilder) AddBrand(bnd string) Builder {
	this.ACar.Brand = bnd
	return this
}

func (this *ConcreteBuilder) SetType(t string) Builder {
	this.ACar.Type = t
	return this
}

func (this *ConcreteBuilder) Build() Car {
	return this.ACar
}

// Director 角色
type Director struct {
	Builder Builder
}

func main() {
	dr := Director{&ConcreteBuilder{}}
	adCar := dr.Builder.SetType("SUV").AddBrand("奥迪").PaintColor("white").Build()
	adCar.Drive()

	bwCar := dr.Builder.SetType("sporting").AddBrand("宝马").PaintColor("red").Build()
	bwCar.Drive()
}

单例模式

单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。

单例模式的要点有三个:
一是某个类只能有一个实例;
二是它必须自行创建这个实例;
三是它必须自行向整个系统提供这个实例。

用 sync.Once 确保返回唯一实例
golang代码事例如下:

package main

import (
	"fmt"
	"sync"
)

// Singleton 是单例模式类
type Singleton struct{}

var singleton *Singleton
var once sync.Once // 确保返回唯一实例

// GetInstance 用于获取单例模式对象
func GetInstance() *Singleton {
	once.Do(func() {
		singleton = &Singleton{}
	})
	return singleton
}

func main() {
	ins1 := GetInstance()
	ins2 := GetInstance()
	if ins1 != ins2 {
		fmt.Println("instance is not equal")
	} else {
		fmt.Println("this is an equal instance")
	}
}

猜你喜欢

转载自blog.csdn.net/af2251337/article/details/89674389