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/zh-hk/n/370218.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
HJNSZ的頭像HJNSZ
上一篇 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

發表回復

登錄後才能評論