一、简介
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