GOF23设计模式详解

一、简介

GOF23即Gang of Four 23 Design Patterns,是对面向对象设计模式的经典总结和归纳。GOF23一共包含23种设计模式,分别是创建型模式、结构型模式和行为型模式,旨在提供一种在软件开发中面向对象设计的模板,这些模板可以让开发者更容易地设计出高质量的软件。

二、创建型模式

1. 工厂模式

工厂模式用于创建对象,它将对象的创建工作交给具体的工厂进行处理,而不是由客户端直接生成。

type Shape interface {
	draw()
}

type Circle struct{}

func (c *Circle) draw() {
	fmt.Println("Draw a circle.")
}

type Rectangle struct{}

func (r *Rectangle) draw() {
	fmt.Println("Draw a rectangle.")
}

type ShapeFactory struct{}

func (f *ShapeFactory) getShape(shapeType string) Shape {
	switch shapeType {
	case "circle":
		return &Circle{}
	case "rectangle":
		return &Rectangle{}
	default:
		return nil
	}
}

2. 抽象工厂模式

抽象工厂模式用于创建一系列相关的对象,它将对象的创建工作交给具体的工厂进行处理。

type Shape interface {
	draw()
}

type Color interface {
	fill()
}

type Circle struct{}

func (c *Circle) draw() {
	fmt.Println("Draw a circle.")
}

type Rectangle struct{}

func (r *Rectangle) draw() {
	fmt.Println("Draw a rectangle.")
}

type Red struct{}

func (r *Red) fill() {
	fmt.Println("Fill with red color.")
}

type Blue struct{}

func (b *Blue) fill() {
	fmt.Println("Fill with blue color.")
}

type ShapeFactory interface {
	getShape(shapeType string) Shape
}

type ColorFactory interface {
	getColor(colorType string) Color
}

type AbstractFactory interface {
	getShapeFactory() ShapeFactory
	getColorFactory() ColorFactory
}

type ShapeFactory1 struct{}

func (f *ShapeFactory1) getShape(shapeType string) Shape {
	switch shapeType {
	case "circle":
		return &Circle{}
	case "rectangle":
		return &Rectangle{}
	default:
		return nil
	}
}

type ColorFactory1 struct{}

func (f *ColorFactory1) getColor(colorType string) Color {
	switch colorType {
	case "red":
		return &Red{}
	case "blue":
		return &Blue{}
	default:
		return nil
	}
}

type ConcreteFactory1 struct{}

func (f *ConcreteFactory1) getShapeFactory() ShapeFactory {
	return &ShapeFactory1{}
}

func (f *ConcreteFactory1) getColorFactory() ColorFactory {
	return &ColorFactory1{}
}

3. 单例模式

单例模式是一种保证类只有一个实例,且自行实例化并向整个系统提供这个实例的模式。

type Singleton struct{}

var singletonInstance *Singleton
var once sync.Once

func GetInstance() *Singleton {
	once.Do(func() {
		singletonInstance = &Singleton{}
	})
	return singletonInstance
}

三、结构型模式

1. 适配器模式

适配器模式是一种将一个类的接口转换成另外一种接口的模式,以满足客户端的需求。

type MediaPlayer interface {
	play(audioType string, filename string)
}

type AdvancedMediaPlayer interface {
	playVlc(filename string)
	playMp4(filename string)
}

type VlcPlayer struct{}
type Mp4Player struct{}

func (p *VlcPlayer) playVlc(filename string) {
	fmt.Printf("Playing vlc file: %s\n", filename)
}

func (p *Mp4Player) playMp4(filename string) {
	fmt.Printf("Playing mp4 file: %s\n", filename)
}

type MediaAdapter struct {
	advancedMediaPlayer AdvancedMediaPlayer
}

func (a *MediaAdapter) play(audioType string, filename string) {
	if audioType == "vlc" {
		a.advancedMediaPlayer.playVlc(filename)
	} else if audioType == "mp4" {
		a.advancedMediaPlayer.playMp4(filename)
	}
}

type AudioPlayer struct {
	mediaAdapter MediaAdapter
}

func (p *AudioPlayer) play(audioType string, filename string) {
	if audioType == "mp3" {
		fmt.Printf("Playing mp3 file: %s\n", filename)
	} else if audioType == "vlc" || audioType == "mp4" {
		p.mediaAdapter = MediaAdapter{&Mp4Player{}}
		p.mediaAdapter.play(audioType, filename)
	}
}

2. 桥接模式

桥接模式是一种将抽象部分与实现部分分离的模式,以便两者能够独立变化。

type Color interface {
	fill()
}

type Shape interface {
	draw()
	setColor(color Color)
}

type Circle struct {
	color Color
}

func (c *Circle) draw() {
	fmt.Println("Draw a circle.")
}

func (c *Circle) setColor(color Color) {
	c.color = color
}

type Rectangle struct {
	color Color
}

func (r *Rectangle) draw() {
	fmt.Println("Draw a rectangle.")
}

func (r *Rectangle) setColor(color Color) {
	r.color = color
}

type Red struct{}

func (r *Red) fill() {
	fmt.Println("Fill with red color.")
}

type Blue struct{}

func (b *Blue) fill() {
	fmt.Println("Fill with blue color.")
}

type AbstractShape interface {
	draw()
	setColor(color Color)
}

type AbstractColor interface {
	fill()
}

type AbstractBridge struct {
	shape AbstractShape
	color AbstractColor
}

func (b *AbstractBridge) drawWithColor() {
	b.shape.draw()
	b.color.fill()
}

type RedCircle struct {
	color Color
}

func (c *RedCircle) draw() {
	fmt.Println("Draw a red circle.")
}

func (c *RedCircle) setColor(color Color) {
	c.color = color
}

type BlueRectangle struct {
	color Color
}

func (r *BlueRectangle) draw() {
	fmt.Println("Draw a blue rectangle.")
}

func (r *BlueRectangle) setColor(color Color) {
	r.color = color
}

3. 装饰器模式

装饰器模式是一种为已有的对象动态地添加功能的模式,不改变其接口。

type Shape interface {
	draw()
}

type Circle struct{}

func (c *Circle) draw() {
	fmt.Println("Draw a circle.")
}

type Rectangle struct{}

func (r *Rectangle) draw() {
	fmt.Println("Draw a rectangle.")
}

type ShapeDecorator struct {
	shape Shape
}

func (d *ShapeDecorator) draw() {
	d.shape.draw()
}

type ColorShapeDecorator struct {
	ShapeDecorator
	color string
}

func (d *ColorShapeDecorator) draw() {
	fmt.Printf("Draw a %s %s\n", d.color, reflect.TypeOf(d.ShapeDecorator.shape).Elem().Name())
}

四、行为型模式

1. 观察者模式

观察者模式是一种对象间的一对多依赖关系,当一个对象状态发生改变时,所有依赖于它的对象都会得到通知。

type Subject interface {
	registerObserver(observer Observer)
	removeObserver(observer Observer)
	notifyObservers()
}

type Observer interface {
	update(state string)
}

type WeatherData struct {
	observers []Observer
	state     string
}

func (d *WeatherData) registerObserver(observer Observer) {
	d.observers = append(d.observers, observer)
}

func (d *WeatherData) removeObserver(observer Observer) {
	for i, obs := range d.observers {
		if obs == observer {
			d.observers = append(d.observers[:i], d.observers[i+1:]...)
			break
		}
	}
}

func (d *WeatherData) notifyObservers() {
	for _, obs := range d.observers {
		obs.update(d.state)
	}
}

type CurrentConditionsDisplay struct {
	state string
}

func (d *CurrentConditionsDisplay) update(state string) {
	d.state = state
	fmt.Printf("Current conditions: %s\n", state)
}

2. 命令模式

命令模式是一种将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象的模式。

type Command interface {
	execute()
}

type Light struct{}

func (l *Light) on() {
	fmt.Println("Light is on.")
}

func (l *Light) off() {
	fmt.Println("Light is off.")
}

type LightOnCommand struct {
	light *Light
}

func (c *LightOnCommand) execute() {
	c.light.on()
}

type LightOffCommand struct {
	light *Light
}

func (c *LightOffCommand) execute() {
	c.light.off()
}

type SimpleRemoteControl struct {
	slot Command
}

func (r *SimpleRemoteControl) setCommand(command Command) {
	r.slot = command
}

func (r *SimpleRemoteControl) buttonPressed() {
	r.slot.execute()
}

3. 责任链模式

责任链模式是一种为解除请求的发送者和请求的接收者之间耦合关系的模式,将多个对象连成一条链,并沿着这条链传递请求,直到有对象处理它为止。

type Request struct {
	msg string
}

type Response struct {
	res string
}

type Filter interface {
	doFilter(req *Request, resp *Response, chain *FilterChain)
}

type FilterChain struct {
	filters []Filter
	index   int
}

func (c *FilterChain) addFilter(filter Filter) {
	c.filters = append(c.filters, filter)
}

func (c *FilterChain) doFilter(req *Request, resp *Response) {
	if c.index == len(c.filters) {
		return
	}
	filter := c.filters[c.index]
	c.index++
	filter.doFilter(req, resp, c)
}

type LogFilter struct{}

func (f *LogFilter) doFilter(req *Request, resp *Response, chain *FilterChain) {
	fmt.Printf("Log filter, request msg: %s\n", req.msg)
	chain.doFilter(req, resp)
	fmt.Printf("Log filter, response: %s\n", resp.res)
}

type HelloFilter struct{}

func (f *HelloFilter) doFilter(req *Request, resp *Response, chain *FilterChain) {
	fmt.Printf("Hello filter, request msg: %s\n", req.msg)
	resp.res += "Hello "
	chain.doFilter(req, resp)
	fmt.Printf("Hello filter, response: %s\n", resp.res)
}

type WorldFilter struct{}

func (f *WorldFilter) doFilter(req *Request, resp *Response, chain *FilterChain) {
	fmt.Printf("World filter, request msg: %s\n", req.msg)
	resp.res += "World"
	chain.doFilter(req, resp)
	fmt.Printf("World filter, response: %s\n", resp.res)
}

原创文章,作者:HJNSZ,如若转载,请注明出处:https://www.506064.com/n/370218.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
HJNSZHJNSZ
上一篇 2025-04-18 13:40
下一篇 2025-04-18 13:40

相关推荐

  • 手机安全模式怎么解除?

    安全模式是一种手机自身的保护模式,它会禁用第三方应用程序并使用仅限基本系统功能。但有时候,安全模式会使你无法使用手机上的一些重要功能。如果你想解除手机安全模式,可以尝试以下方法: …

    编程 2025-04-28
  • Qt State Machine与状态机模式

    本文将介绍Qt State Machine和状态机模式在Qt中的实现。Qt提供了QStateMachine和QState两个类,可以方便地实现状态机模式,并且能有效地处理复杂的、多…

    编程 2025-04-27
  • 显示C++设计模式

    本文将详细介绍显示C++设计模式的概念、类型、优点和代码实现。 一、概念 C++设计模式是在软件设计阶段定义,用于处理常见问题的可重用解决方案。这些解决方案是经过测试和验证的,并已…

    编程 2025-04-27
  • Centos7进入单用户模式的解释

    本文将介绍如何在Centos7中进入单用户模式,并从以下几个方面进行详细的阐述。 一、Centos7进入单用户模式的解答 在Centos7中进入单用户模式需要执行以下步骤: 1. …

    编程 2025-04-27
  • 神经网络代码详解

    神经网络作为一种人工智能技术,被广泛应用于语音识别、图像识别、自然语言处理等领域。而神经网络的模型编写,离不开代码。本文将从多个方面详细阐述神经网络模型编写的代码技术。 一、神经网…

    编程 2025-04-25
  • Linux sync详解

    一、sync概述 sync是Linux中一个非常重要的命令,它可以将文件系统缓存中的内容,强制写入磁盘中。在执行sync之前,所有的文件系统更新将不会立即写入磁盘,而是先缓存在内存…

    编程 2025-04-25
  • Java BigDecimal 精度详解

    一、基础概念 Java BigDecimal 是一个用于高精度计算的类。普通的 double 或 float 类型只能精确表示有限的数字,而对于需要高精度计算的场景,BigDeci…

    编程 2025-04-25
  • Python安装OS库详解

    一、OS简介 OS库是Python标准库的一部分,它提供了跨平台的操作系统功能,使得Python可以进行文件操作、进程管理、环境变量读取等系统级操作。 OS库中包含了大量的文件和目…

    编程 2025-04-25
  • 详解eclipse设置

    一、安装与基础设置 1、下载eclipse并进行安装。 2、打开eclipse,选择对应的工作空间路径。 File -> Switch Workspace -> [选择…

    编程 2025-04-25
  • MPU6050工作原理详解

    一、什么是MPU6050 MPU6050是一种六轴惯性传感器,能够同时测量加速度和角速度。它由三个传感器组成:一个三轴加速度计和一个三轴陀螺仪。这个组合提供了非常精细的姿态解算,其…

    编程 2025-04-25

发表回复

登录后才能评论