一、簡介
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
微信掃一掃
支付寶掃一掃