单例模式:
饿汉:

懒汉:

Go优雅完成

工厂模式:
3类:
简单工厂模式:
package main
import "fmt"
// Shape 接口
type Shape interface {
Draw()
}
// Circle 结构体
type Circle struct{}
func (c Circle) Draw() {
fmt.Println("Drawing a Circle")
}
// Rectangle 结构体
type Rectangle struct{}
func (r Rectangle) Draw() {
fmt.Println("Drawing a Rectangle")
}
// 简单工厂函数
func ShapeFactory(shapeType string) Shape {
switch shapeType {
case "circle":
return Circle{}
case "rectangle":
return Rectangle{}
default:
return nil
}
}
func main() {
circle := ShapeFactory("circle")
circle.Draw()
rectangle := ShapeFactory("rectangle")
rectangle.Draw()
}
工厂方法模式
package main
import "fmt"
// Shape 接口
type Shape interface {
Draw()
}
// Circle 结构体
type Circle struct{}
func (c Circle) Draw() {
fmt.Println("Drawing a Circle")
}
// Rectangle 结构体
type Rectangle struct{}
func (r Rectangle) Draw() {
fmt.Println("Drawing a Rectangle")
}
// ShapeFactory 接口
type ShapeFactory interface {
CreateShape() Shape
}
// CircleFactory 结构体
type CircleFactory struct{}
func (cf CircleFactory) CreateShape() Shape {
return Circle{}
}
// RectangleFactory 结构体
type RectangleFactory struct{}
func (rf RectangleFactory) CreateShape() Shape {
return Rectangle{}
}
func main() {
var factory ShapeFactory
factory = CircleFactory{}
circle := factory.CreateShape()
circle.Draw() // 输出:Drawing a Circle
factory = RectangleFactory{}
rectangle := factory.CreateShape()
rectangle.Draw() // 输出:Drawing a Rectangle
}
抽象工厂模式
package main
import "fmt"
// Shape 接口
type Shape interface {
Draw()
}
// Color 接口
type Color interface {
Fill()
}
// Circle 结构体
type Circle struct{}
func (c Circle) Draw() {
fmt.Println("Drawing a Circle")
}
type Rectangle struct{}
func (r Rectangle) Draw() {
fmt.Println("Drawing a Rectangle")
}
// Red 结构体
type Red struct{}
func (r Red) Fill() {
fmt.Println("Filling with Red color")
}
type Blue struct{}
func (b Blue) Fill() {
fmt.Println("Filling with Blue color")
}
// AbstractFactory 接口
type AbstractFactory interface {
CreateShape() Shape
CreateColor() Color
}
// ShapeFactory 结构体
type ShapeFactory struct {
shapeType string
}
func (sf ShapeFactory) CreateShape() Shape {
if sf.shapeType == "circle" {
return Circle{}
} else if sf.shapeType == "rectangle" {
return Rectangle{}
}
return nil
}
func (sf ShapeFactory) CreateColor() Color {
// 此处可以实现颜色的逻辑
return nil
}
func main() {
shapeFactory := ShapeFactory{shapeType: "circle"}
shape := shapeFactory.CreateShape()
shape.Draw() // 输出:Drawing a Circle
colorFactory := ShapeFactory{shapeType: "red"}
color := colorFactory.CreateColor()
if color != nil {
color.Fill() // 输出:Filling with Red color (需要实现填充逻辑)
}
}
641

被折叠的 条评论
为什么被折叠?



