1. 策略模式实现代码
package main
import (
"fmt"
)
// 定义图形接口
type Shape interface {
Draw()
}
// 圆形结构体及绘制方法
type Circle struct {
Radius float64
}
func (c Circle) Draw() {
fmt.Printf("绘制圆形,半径: %.2f\n", c.Radius)
}
// 矩形结构体及绘制方法
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Draw() {
fmt.Printf("绘制矩形,宽: %.2f,高: %.2f\n", r.Width, r.Height)
}
// 三角形结构体及绘制方法
type Triangle struct {
Base float64
Height float64
}
func (t Triangle) Draw() {
fmt.Printf("绘制三角形,底: %.2f,高: %.2f\n", t.Base, t.Height)
}
// 图形绘制器结构体,持有Shape接口
type ShapeDrawer struct {
Shape Shape
}
// 绘制器的绘制方法,调用具体图形的绘制逻辑
func (sd ShapeDrawer) Draw() {
sd.Shape.Draw()
}
2. 使用示例
func main() {
circle := Circle{Radius: 5.0}
circleDrawer := ShapeDrawer{Shape: circle}
circleDrawer.Draw()
rectangle := Rectangle{Width: 10.0, Height: 5.0}
rectangleDrawer := ShapeDrawer{Shape: rectangle}
rectangleDrawer.Draw()
triangle := Triangle{Base: 8.0, Height: 6.0}
triangleDrawer := ShapeDrawer{Shape: triangle}
triangleDrawer.Draw()
}
3. 策略模式优势
- 可维护性:每种图形的绘制逻辑独立在各自的结构体方法中,当需要修改某个图形的绘制逻辑时,不会影响其他图形的代码,提高了代码的可维护性。
- 可扩展性:新增一种图形时,只需要实现Shape接口,然后在使用处创建相应的图形对象并放入ShapeDrawer即可,无需修改原有图形的绘制代码,符合开闭原则。
- 灵活性:不同的图形绘制逻辑可以在运行时动态切换,通过改变ShapeDrawer持有的Shape对象来实现不同图形的绘制。
4. 代码解耦与扩展
- 解耦:将图形的绘制逻辑与使用图形绘制的代码解耦。ShapeDrawer只依赖于Shape接口,而不依赖于具体的图形实现类,降低了模块之间的耦合度。
- 扩展:如果要新增一种图形,比如菱形,只需要创建菱形结构体并实现Shape接口的Draw方法,然后就可以像其他图形一样使用ShapeDrawer来绘制,无需修改原有图形的代码和ShapeDrawer的代码,实现了代码的低耦合和高扩展性。