01 Go 24 design patterns-creative patterns
Design Pattern is a common solution to common problems in software engineering.
They are not concrete code, but proven best practices that help developers design flexible, maintainable and scalable software systems
Benefits of using design patterns
- Interview
- Improve code reusability and write high-quality code
- The best practices summarized by predecessors, using the appropriate design pattern in the right place can get twice the result with half the effort.
Creational mode
In the Go language, Creational Patterns are a type of design pattern used to handle object creation. Their main goal is to provide a flexible way to create objects while hiding the specific details of object creation, thereby reducing code coupling and improving code reusability and maintainability.
For example, http.NewRequest(), bytes.NewReader(), md5.New()
The core idea of the creational pattern is to separate the creation and use of objects, so that the system does not rely on specific object creation methods, but relies on abstraction.
Singleton mode Singleton
Make sure there is only one instance of a class and provide a global access point.
Applicable scenarios:
- Scenarios that require globally unique instances such as configuration management, logging, and database connection pools.
In the project before, we have been using global.DB and global.Config. It is actually similar to this, but it is not a singleton mode because it is the corresponding object used directly instead of the object returned by the function.
package main
import (
"fmt"
)
type DB struct {
Database string
}
var db *DB
func GetDB() *DB {
db = &DB{
Database: "fengfeng",
}
return db
}
func main() {
d := db
fmt.Printf("%p, %v\n", d, d.Database)
}
Previously, global variables were used directly, but this variable could be nil. In this case, using it again would result in a null pointer.

Then you can use a function to make a judgment in it. If the object is nil, initialize the object. If there is one later, just return the previously created object directly.
package main
import (
"fmt"
"sync"
)
type DB struct {
Database string
}
var db *DB
var once sync.Once
func GetDB() *DB {
once.Do(func() {
db = &DB{
Database: "fengfeng",
}
})
return db
}
func main() {
d := GetDB()
fmt.Printf("%p, %v\n", d, d.Database)
d = GetDB()
fmt.Printf("%p, %v\n", d, d.Database)
}
Simple Factory Pattern Simple Factory Pattern
Their goal is to separate the creation and use of objects, thereby reducing the coupling of the code.
However, specific factories still differ.
| Mode | Features | Applicable Scenarios |
|---|---|---|
| Simple Factory | A factory class is responsible for creating all products, and determines which product to create through conditional judgment. | There are fewer product types and the creation logic is simple. |
| Factory Method Pattern | Each product corresponds to a factory class, which conforms to the opening and closing principle. | There are many types of products and the creation logic is complex. |
| Abstract Factory Pattern | Each factory class can create a set of related products, emphasizing the concept of product family. | A scene where a set of related objects needs to be created. |
Simple Factory is not a formal design pattern, but a programming habit. It encapsulates the object creation logic through a factory class. The client only needs to pass parameters to the factory class, and the factory class decides what kind of object to create.
Features:
- There is only one factory class responsible for creating all products.
- Decide which product to create through conditional judgment (such as
switchorif-else).
Applicable scenarios:
- There are fewer product types and create scenarios with simple logic.
Opening and closing principle: When requirements change, the functionality of the system can be expanded by adding new code instead of modifying existing code.
package main
import "fmt"
type Product interface {
Use()
}
type ProductA struct{}
func (p *ProductA) Use() {
fmt.Println("Using Product A")
}
type ProductB struct{}
func (p *ProductB) Use() {
fmt.Println("Using Product B")
}
func CreateProduct(productType string) Product {
switch productType {
case "A":
return &ProductA{}
case "B":
return &ProductB{}
default:
return nil
}
}
func main() {
productA := CreateProduct("A")
productA.Use()
productB := CreateProduct("B")
productB.Use()
}
Advantages:
- Simple and easy to use, suitable for small projects.
Disadvantages:
- It does not comply with the Open-Closed Principle (OCP), and the factory class needs to be modified when adding new products.
Factory Method Pattern Factory Method
In the previous simple factory model, one factory was responsible for the production of several products.
The factory method pattern defines an interface for creating objects, but defers the specific creation logic to subclasses. Each subclass is responsible for creating a specific product.
Features:
- Each product corresponds to a factory class.
- Complying with the opening and closing principle, when adding new products, you only need to add a new factory class without modifying the existing code.
Applicable scenarios:
- There are many types of products and create scenarios with complex logic.
package main
import "fmt"
type Database interface {
Connect() string
}
// MySQL 操作
type MySQL struct{}
func (m *MySQL) Connect() string {
return "Connected to MySQL"
}
// PostgreSQL 操作
type PostgreSQL struct{}
func (p *PostgreSQL) Connect() string {
return "Connected to PostgreSQL"
}
// DatabaseFactory 工厂接口
type DatabaseFactory interface {
CreateDatabase() Database
}
// MySQLFactory MySQL 工厂
type MySQLFactory struct{}
func (m *MySQLFactory) CreateDatabase() Database {
return &MySQL{}
}
// PostgreSQL 工厂
type PostgreSQLFactory struct{}
func (p *PostgreSQLFactory) CreateDatabase() Database {
return &PostgreSQL{}
}
// UseDatabase 使用数据库
func UseDatabase(factory DatabaseFactory) {
db := factory.CreateDatabase()
fmt.Println(db.Connect())
}
func main() {
// 使用 MySQL
mysqlFactory := &MySQLFactory{}
UseDatabase(mysqlFactory)
// 使用 PostgreSQL
postgresFactory := &PostgreSQLFactory{}
UseDatabase(postgresFactory)
}
Advantages:
- Complies with the opening and closing principle and has strong scalability.
- Each factory is only responsible for the creation of one product and has a single responsibility.
Disadvantages:
-The number of classes will increase and the system complexity will increase.
Abstract Factory Pattern Abstract Factory
The Abstract Factory pattern provides an interface for creating a series of related or interdependent objects without specifying their concrete classes. It is suitable for scenarios where you need to create a set of related products.
Features:
- Each factory class can create multiple related products.
- Emphasis on the concept of product families, such as different style components (Windows style, Mac style) in GUI libraries.
Applicable scenarios:
- A scene where a set of related objects needs to be created.
package main
import "fmt"
// DBConnection 抽象产品:数据库连接接口
type DBConnection interface {
Connect() string
}
// DBCommand 抽象产品:数据库命令接口
type DBCommand interface {
Execute(query string) string
}
// MySQLConnection 具体产品:MySQL 连接
type MySQLConnection struct{}
func (m *MySQLConnection) Connect() string {
return "Connected to MySQL"
}
// MySQLCommand 具体产品:MySQL 命令
type MySQLCommand struct{}
func (m *MySQLCommand) Execute(query string) string {
return fmt.Sprintf("MySQL executing query: %s", query)
}
// PostgreSQLConnection 具体产品:PostgreSQL 连接
type PostgreSQLConnection struct{}
func (p *PostgreSQLConnection) Connect() string {
return "Connected to PostgreSQL"
}
// PostgreSQLCommand 具体产品:PostgreSQL 命令
type PostgreSQLCommand struct{}
func (p *PostgreSQLCommand) Execute(query string) string {
return fmt.Sprintf("PostgreSQL executing query: %s", query)
}
// DBFactory 抽象工厂接口
type DBFactory interface {
CreateConnection() DBConnection
CreateCommand() DBCommand
}
// MySQLFactory 具体工厂:MySQL 工厂
type MySQLFactory struct{}
func (m *MySQLFactory) CreateConnection() DBConnection {
return &MySQLConnection{}
}
func (m *MySQLFactory) CreateCommand() DBCommand {
return &MySQLCommand{}
}
// PostgreSQLFactory 具体工厂:PostgreSQL 工厂
type PostgreSQLFactory struct{}
func (p *PostgreSQLFactory) CreateConnection() DBConnection {
return &PostgreSQLConnection{}
}
func (p *PostgreSQLFactory) CreateCommand() DBCommand {
return &PostgreSQLCommand{}
}
func UseDatabase(factory DBFactory) {
connection := factory.CreateConnection()
command := factory.CreateCommand()
fmt.Println(connection.Connect())
fmt.Println(command.Execute("SELECT * FROM users"))
}
func main() {
// 使用 MySQL
mysqlFactory := &MySQLFactory{}
UseDatabase(mysqlFactory)
// 使用 PostgreSQL
postgresFactory := &PostgreSQLFactory{}
UseDatabase(postgresFactory)
}
Advantages:
- A set of related objects can be created to ensure compatibility between objects.
- Complies with the opening and closing principle and has strong scalability.
Disadvantages:
-The number of classes will increase and the system complexity will increase.
- When adding a new product family or product hierarchy, the abstract factory interface and all its implementation classes need to be modified.
The difference between abstract factory pattern and factory method pattern
| Features | Factory Method Pattern | Abstract Factory Pattern |
|---|---|---|
| Number of products | A factory method only creates one product. | An abstract factory creates multiple related products (product families). |
| Product Relationship | There is no direct relationship between products. | Products are related (belong to the same product family). |
| Extensibility | Specific factory classes need to be added when extending. | When expanding, you need to add specific factory classes and product families. |
| Implementation | Implemented through inheritance. | Achieved through composition. |
| Applicable Scenarios | Creation of a single product. | Creation of multiple related products. |
- Factory Method Pattern is simpler and suitable for the creation of a single product.
- Abstract Factory Pattern is more powerful and suitable for creating multiple related products, but the implementation is also more complex.
Builder mode Builder
It is used to build complex objects step by step. The core idea of the builder pattern is to separate the construction process of a complex object from its representation, so that the same construction process can create different representations.
Builder pattern is particularly suitable for the following scenarios:
- The construction process of the object is very complex and consists of multiple steps.
- The object's construction process needs to support different configurations or representations.
package main
import "fmt"
// 产品:House
type House struct {
Walls string
Roof string
Windows string
Doors string
}
func (h *House) Show() {
fmt.Printf("House with %s walls, %s roof, %s windows, and %s doors\n",
h.Walls, h.Roof, h.Windows, h.Doors)
}
// 建造者接口
type HouseBuilder interface {
BuildWalls()
BuildRoof()
BuildWindows()
BuildDoors()
GetHouse() *House
}
// 具体建造者:ConcreteHouseBuilder
type ConcreteHouseBuilder struct {
house *House
}
func NewConcreteHouseBuilder() *ConcreteHouseBuilder {
return &ConcreteHouseBuilder{house: &House{}}
}
func (b *ConcreteHouseBuilder) BuildWalls() {
b.house.Walls = "concrete"
}
func (b *ConcreteHouseBuilder) BuildRoof() {
b.house.Roof = "tile"
}
func (b *ConcreteHouseBuilder) BuildWindows() {
b.house.Windows = "glass"
}
func (b *ConcreteHouseBuilder) BuildDoors() {
b.house.Doors = "wooden"
}
func (b *ConcreteHouseBuilder) GetHouse() *House {
return b.house
}
// 指挥者
type Director struct {
builder HouseBuilder
}
func NewDirector(builder HouseBuilder) *Director {
return &Director{builder: builder}
}
func (d *Director) Construct() {
d.builder.BuildWalls()
d.builder.BuildRoof()
d.builder.BuildWindows()
d.builder.BuildDoors()
}
// 客户端代码
func main() {
// 创建具体建造者
builder := NewConcreteHouseBuilder()
// 创建指挥者
director := NewDirector(builder)
// 指挥者构建产品
director.Construct()
// 获取最终产品
house := builder.GetHouse()
house.Show()
}
Prototype pattern
It creates new objects by copying existing objects rather than creating new classes. The core idea of the prototype pattern is to use the cloning ability of objects to avoid repeated initialization, which is especially suitable for objects with high creation costs.
package main
import "fmt"
// Prototype 原型接口
type Prototype interface {
Clone() Prototype
}
// ConcretePrototype 具体原型
type ConcretePrototype struct {
Name string
Age int
}
func (p *ConcretePrototype) Clone() Prototype {
// 创建一个新对象,并复制当前对象的属性
return &ConcretePrototype{
Name: p.Name,
Age: p.Age,
}
}
func (p *ConcretePrototype) String() string {
return fmt.Sprintf("Name: %s, Age: %d", p.Name, p.Age)
}
func main() {
// 创建原型对象
prototype := &ConcretePrototype{
Name: "Alice",
Age: 25,
}
// 克隆原型对象
clone := prototype.Clone().(*ConcretePrototype)
// 修改克隆对象的属性
clone.Name = "Bob"
clone.Age = 30
// 输出原型对象和克隆对象
fmt.Println("Prototype:", prototype)
fmt.Println("Clone:", clone)
}
Using prototype mode, if there is a reference type, you need to consider the issues of deep copy and shallow copy.
A shallow copy only copies the object itself and not the objects it references, while a deep copy recursively copies the entire object graph.
This requires choosing an appropriate copy method based on your needs.
02 Golang 24 design patterns - structural pattern
Structural Pattern (Structural Pattern), which mainly focuses on how to combine classes or objects into larger structures to achieve new functions or optimize the system structure without changing the original classes or objects.
The core idea of the structural pattern is to achieve code reuse and extension through composition rather than inheritance. They help developers design flexible and scalable system structures while reducing the coupling between classes.
Proxy mode Proxy
It controls access to another object by providing a proxy object. The core idea of the proxy pattern is to enhance or restrict access to the original object through a proxy object without changing the original object.
Proxy mode is usually used in the following scenarios:
- Lazy initialization: When the creation cost of the object is high, the initialization of the object can be delayed through the proxy.
- Access Control: Restrict access to the original object through proxy objects.
- Logging: Record access logs to the original object through the proxy object.
- Cache: Cache the results of the original object through the proxy object to avoid repeated calculations.
package main
import (
"fmt"
"time"
)
// 主题接口
type Subject interface {
Request()
}
// 真实对象
type RealSubject struct{}
func (r *RealSubject) Request() {
fmt.Println("RealSubject: Handling Request")
}
// 代理对象
type Proxy struct {
realSubject *RealSubject
}
func NewProxy() *Proxy {
return &Proxy{}
}
func (p *Proxy) Request() {
// 延迟初始化真实对象
if p.realSubject == nil {
fmt.Println("Proxy: Lazy Initializing RealSubject")
p.realSubject = &RealSubject{}
}
// 访问控制
fmt.Println("Proxy: Checking Access")
time.Sleep(1 * time.Second) // 模拟访问控制逻辑
// 调用真实对象的方法
p.realSubject.Request()
// 日志记录
fmt.Println("Proxy: Logging Request")
}
// 客户端代码
func main() {
proxy := NewProxy()
// 通过代理对象访问真实对象
proxy.Request()
}
Bridge mode Bridge
Its core idea is to separate the abstract part from the implementation part so that they can change independently. In this way, the bridge pattern can avoid the explosion of the number of classes (that is, the combination of classes grows exponentially) while improving the scalability and maintainability of the code.
For example:
Let's say you have two computers: a Mac and a Windows. There are also two printers: Epson and HP. The two computers and printers may be used in any combination.
At first, the function will be written like this. Windows combines Epson and HP, and Mac combines Epson and HP. When printing, you call your own print method.
// Mac + Epson
type MacEpson struct{}
func (m *MacEpson) Print() {
fmt.Println("Print request for mac")
fmt.Println("Printing by a EPSON Printer")
}
// Mac + HP
type MacHp struct{}
func (m *MacHp) Print() {
fmt.Println("Print request for mac")
fmt.Println("Printing by a HP Printer")
}
// Windows + Epson
type WindowsEpson struct{}
func (w *WindowsEpson) Print() {
fmt.Println("Print request for windows")
fmt.Println("Printing by a EPSON Printer")
}
// Windows + HP
type WindowsHp struct{}
func (w *WindowsHp) Print() {
fmt.Println("Print request for windows")
fmt.Println("Printing by a HP Printer")
}
However, if a new printer is introduced, the amount of code will increase exponentially.
Therefore, we need to decouple the computer and the printer. The computer's print method is bridged to the selected printer's print method.
The code is as follows:
package main
import "fmt"
// 1. 定义 Printer 接口(实现层)
type Printer interface {
PrintFile()
}
// 2. 定义 Epson 打印机(具体实现)
type Epson struct{}
func (p *Epson) PrintFile() {
fmt.Println("Printing by a EPSON Printer")
}
// 3. 定义 HP 打印机(具体实现)
type Hp struct{}
func (p *Hp) PrintFile() {
fmt.Println("Printing by a HP Printer")
}
// 4. 定义 Computer 接口(抽象层)
type Computer interface {
Print()
SetPrinter(Printer)
}
// 5. 定义 Mac 计算机(精确抽象)
type Mac struct {
printer Printer
}
func (m *Mac) Print() {
fmt.Println("Print request for mac")
m.printer.PrintFile()
}
func (m *Mac) SetPrinter(p Printer) {
m.printer = p
}
// 6. 定义 Windows 计算机(精确抽象)
type Windows struct {
printer Printer
}
func (w *Windows) Print() {
fmt.Println("Print request for windows")
w.printer.PrintFile()
}
func (w *Windows) SetPrinter(p Printer) {
w.printer = p
}
// 7. 客户端代码
func main() {
// 创建打印机实例
hpPrinter := &Hp{}
epsonPrinter := &Epson{}
// 创建计算机实例
macComputer := &Mac{}
winComputer := &Windows{}
// Mac 使用 HP 打印机
macComputer.SetPrinter(hpPrinter)
macComputer.Print()
fmt.Println()
// Mac 使用 Epson 打印机
macComputer.SetPrinter(epsonPrinter)
macComputer.Print()
fmt.Println()
// Windows 使用 HP 打印机
winComputer.SetPrinter(hpPrinter)
winComputer.Print()
fmt.Println()
// Windows 使用 Epson 打印机
winComputer.SetPrinter(epsonPrinter)
winComputer.Print()
fmt.Println()
}
Advantages of bridge mode
- Decoupling:
- The abstract part and the implementation part can be changed independently without affecting each other.
- Modifying the implementation part will not affect the code of the abstract part.
- Flexibility:
- Implementation parts can be switched dynamically (e.g., implementation replacement at runtime).
- Scalability:
- When adding a new abstract part or implementation part, there is no need to modify the existing code.
- Avoid class explosion:
- Avoiding exponential growth in the number of classes by replacing inheritance with composition.
Composite mode Composite
It allows you to combine objects into a tree structure to represent "part-whole" hierarchical relationships. The composition pattern allows clients to uniformly handle individual objects and combinations of objects.
Application scenarios:
- File system: For example, in the management of directories and files, folders can be regarded as combination nodes and files as leaf nodes through the combination mode.
- Organizational structure: For example, the relationship between departments and employees within a company, departments can be regarded as combination nodes and employees as leaf nodes through the combination model.
package main
import (
"fmt"
)
// FileSystemNode 组件接口:文件系统节点
type FileSystemNode interface {
Display(indent string)
}
// File 叶子节点:文件
type File struct {
name string
}
func (f *File) Display(indent string) {
fmt.Println(indent + f.name)
}
// Folder 组合节点:文件夹
type Folder struct {
name string
children []FileSystemNode
}
func (f *Folder) Display(indent string) {
fmt.Println(indent + f.name)
for _, child := range f.children {
child.Display(indent + " ")
}
}
func (f *Folder) Add(child FileSystemNode) {
f.children = append(f.children, child)
}
// 客户端代码
func main() {
// 创建文件
file1 := &File{name: "file1.txt"}
file2 := &File{name: "file2.txt"}
file3 := &File{name: "file3.txt"}
// 创建文件夹
folder1 := &Folder{name: "Folder1"}
folder2 := &Folder{name: "Folder2"}
// 将文件添加到文件夹
folder1.Add(file1)
folder1.Add(file2)
folder2.Add(file3)
// 将文件夹添加到另一个文件夹
rootFolder := &Folder{name: "Root"}
rootFolder.Add(folder1)
rootFolder.Add(folder2)
// 显示文件系统结构
rootFolder.Display("")
}
Why use combined mode?
- Simplify client code: The client can treat single objects and object combinations consistently without caring about their specific types.
- Enhanced flexibility: New components can be easily added or the structure of existing components can be modified without modifying existing code.
- Improve scalability: Support recursive combination, making complex hierarchical structures easy to build and maintain.
Decorator pattern Decorator
It allows you to dynamically add behaviors or responsibilities to an object without modifying the object's original class. By introducing decorator classes, different functionality can be flexibly combined at runtime without the need to create a large number of subclasses. The core idea of the decorator pattern is to wrap an object in one or more decorators, each of which can add additional behavior before or after calling the decorated object's method.
Suppose you are developing a web service in which one of the core functions is to handle user requests. Now, you need to add the following functionality for request handling without modifying the core functional code:
- Logging: Record the details of each request.
- Performance monitoring: Record the processing time of each request.
Using the decorator pattern, you can easily implement these features without modifying the original request processing logic.
package main
import (
"fmt"
"time"
)
// RequestHandler 组件接口:请求处理器
type RequestHandler interface {
HandleRequest(url string) string
}
// CoreRequestHandler 具体组件:核心请求处理器
type CoreRequestHandler struct{}
func (c *CoreRequestHandler) HandleRequest(url string) string {
// 模拟请求处理
time.Sleep(100 * time.Millisecond)
return fmt.Sprintf("Response from %s", url)
}
// LoggingDecorator 装饰器:日志记录
type LoggingDecorator struct {
handler RequestHandler
}
func (l *LoggingDecorator) HandleRequest(url string) string {
// 记录请求日志
fmt.Printf("Logging: Handling request for %s\n", url)
// 调用原始处理器
response := l.handler.HandleRequest(url)
// 记录响应日志
fmt.Printf("Logging: Response for %s: %s\n", url, response)
return response
}
// PerformanceMonitorDecorator 装饰器:性能监控
type PerformanceMonitorDecorator struct {
handler RequestHandler
}
func (p *PerformanceMonitorDecorator) HandleRequest(url string) string {
// 记录开始时间
start := time.Now()
// 调用原始处理器
response := p.handler.HandleRequest(url)
// 记录处理时间
duration := time.Since(start)
fmt.Printf("Performance: Request for %s took %v\n", url, duration)
return response
}
// 客户端代码
func main() {
// 创建核心请求处理器
coreHandler := &CoreRequestHandler{}
// 添加日志记录功能
loggingHandler := &LoggingDecorator{coreHandler}
// 添加性能监控功能
monitoredHandler := &PerformanceMonitorDecorator{loggingHandler}
// 处理请求
response := monitoredHandler.HandleRequest("/api/data")
fmt.Println(response)
}
Advantages of the decorator pattern
- Dynamic expansion function:
- You can add logging and performance monitoring capabilities to request handlers at runtime without modifying the core request handler code.
- Single responsibility principle:
- Each decorator is only responsible for a specific function (such as logging or performance monitoring), complying with the single responsibility principle.
- Flexibility:
- Decorators can be easily added or removed without affecting other parts of the code.
Adapter mode Adapter
It allows collaboration between incompatible interfaces. The core idea of the adapter pattern is to convert the interface of one class into another interface expected by the client, so that originally incompatible classes can work together.
Suppose your system needs to integrate a third-party payment system, but its interface is incompatible with your system. You can use the adapter pattern to convert the third-party payment system's interface to the interface your system expects.
package main
import "fmt"
// PaymentSystem 目标接口:支付系统
type PaymentSystem interface {
Pay(amount float64) bool
}
// LocalPaymentSystem 具体目标:本地支付系统
type LocalPaymentSystem struct{}
func (l *LocalPaymentSystem) Pay(amount float64) bool {
fmt.Printf("Paid %.2f using local payment system\n", amount)
return true
}
// ThirdPartyPaymentSystem 适配者:第三方支付系统
type ThirdPartyPaymentSystem struct{}
func (t *ThirdPartyPaymentSystem) MakePayment(amount float64) string {
return fmt.Sprintf("Paid %.2f using third-party payment system", amount)
}
// PaymentAdapter 适配器:将第三方支付系统适配到本地支付系统接口
type PaymentAdapter struct {
thirdPartySystem *ThirdPartyPaymentSystem
}
func (p *PaymentAdapter) Pay(amount float64) bool {
result := p.thirdPartySystem.MakePayment(amount)
fmt.Println(result)
return true
}
// 客户端代码
func main() {
// 使用本地支付系统
localPayment := &LocalPaymentSystem{}
localPayment.Pay(100.0)
// 使用适配器将第三方支付系统适配到本地支付系统接口
thirdPartyPayment := &ThirdPartyPaymentSystem{}
adapter := &PaymentAdapter{thirdPartyPayment}
adapter.Pay(200.0)
}
The adapter pattern converts incompatible interfaces into compatible interfaces through an intermediate layer (adapter), so that originally incompatible classes can work together. It is very suitable for integrating third-party libraries, reusing old code or unifying interfaces.
Facade
It provides a unified interface for accessing a set of interfaces in a subsystem. The core idea of the appearance pattern is to simplify the use of complex systems by providing a high-level interface that hides the complexity of the system and makes it easier for clients to use.
Suppose you are developing an e-commerce system, and order processing involves multiple steps (such as inventory checking, payment processing, logistics scheduling, etc.). You can use the facade pattern to encapsulate these steps in a unified interface and simplify client code.
package main
import "fmt"
// Inventory 子系统:库存
type Inventory struct{}
func (i *Inventory) Check() {
fmt.Println("Inventory: Checking stock...")
}
// Payment 子系统:支付
type Payment struct{}
func (p *Payment) Process() {
fmt.Println("Payment: Processing payment...")
}
// Logistics 子系统:物流
type Logistics struct{}
func (l *Logistics) Schedule() {
fmt.Println("Logistics: Scheduling delivery...")
}
// OrderFacade 外观:订单处理
type OrderFacade struct {
inventory *Inventory
payment *Payment
logistics *Logistics
}
func NewOrderFacade() *OrderFacade {
return &OrderFacade{
inventory: &Inventory{},
payment: &Payment{},
logistics: &Logistics{},
}
}
func (o *OrderFacade) PlaceOrder() {
fmt.Println("Placing order...")
o.inventory.Check()
o.payment.Process()
o.logistics.Schedule()
fmt.Println("Order placed successfully!")
}
// 客户端代码
func main() {
orderFacade := NewOrderFacade()
orderFacade.PlaceOrder()
}
Key points of appearance mode
- Simplified interface:
- Facade pattern hides the complexity of subsystems by providing a simple interface.
- Decoupling:
- The client code is decoupled from the subsystem, and changes in the subsystem will not affect the client code.
- Easy to use:
- The client does not need to know the internal details of the subsystem and only needs to call the methods of the facade object.
Flyweight mode Flyweight
It reduces memory usage and improves performance by sharing objects. The core idea of the flyweight pattern is to separate the shared part (internal state) of an object from the unshareable part (external state), thereby reducing the creation of duplicate objects.
For example: shared bicycles and files in Baidu Cloud Disk
The core idea of flyweight model
- Shared objects:
- Flyweight mode reduces memory usage by sharing the same intrinsic state (internal state).
- Separation state:
- Divide the object's state into internal state (shareable) and external state (not shareable).
- Factory management:
- Use factory pattern to manage and reuse flyweight objects.
For example:
In database operations, creating and destroying connections are very time-consuming operations. To improve performance, connection pooling is often used to manage database connections. The core idea of connection pooling is:
- Reuse connection: Obtain the connection from the connection pool, and release the connection back to the connection pool after use instead of destroying it.
- Reduce overhead: avoid frequent creation and destruction of connections, thereby improving performance.
package main
import (
"fmt"
"sync"
)
// Connection 享元接口:数据库连接
type Connection interface {
Execute(query string)
}
// ConcreteConnection 具体享元:数据库连接对象
type ConcreteConnection struct {
id int
}
func (c *ConcreteConnection) Execute(query string) {
fmt.Printf("Connection %d executing query: %s\n", c.id, query)
}
// ConnectionPool 享元工厂:连接池
type ConnectionPool struct {
connections map[int]Connection
mutex sync.Mutex
nextID int
}
func NewConnectionPool() *ConnectionPool {
return &ConnectionPool{
connections: make(map[int]Connection),
nextID: 1,
}
}
// GetConnection 获取连接对象
func (p *ConnectionPool) GetConnection() Connection {
p.mutex.Lock()
defer p.mutex.Unlock()
if len(p.connections) > 0 {
for id, conn := range p.connections {
delete(p.connections, id)
return conn
}
}
// 创建新的连接对象
conn := &ConcreteConnection{id: p.nextID}
p.nextID++
return conn
}
// ReleaseConnection 将连接对象释放回连接池,以便其他客户端可以复用这个连接对象
func (p *ConnectionPool) ReleaseConnection(conn Connection) {
p.mutex.Lock()
defer p.mutex.Unlock()
if c, ok := conn.(*ConcreteConnection); ok {
p.connections[c.id] = c
}
}
// 客户端代码
func main() {
pool := NewConnectionPool()
conn1 := pool.GetConnection()
conn1.Execute("SELECT * FROM users")
pool.ReleaseConnection(conn1)
conn2 := pool.GetConnection()
conn2.Execute("SELECT * FROM orders")
pool.ReleaseConnection(conn2)
}
Key points of flyweight model
- Shared objects:
- Flyweight mode reduces memory usage by sharing the same intrinsic state.
- Separation state:
- Divide the object's state into internal state (shareable) and external state (not shareable).
- Factory management:
- Use factory pattern to manage and reuse flyweight objects.
Reference documentation
Go explanation: combination mode https://blog.csdn.net/zhaoxilengfeng/article/details/144434943
Decorator pattern https://blog.csdn.net/zhaoxilengfeng/article/details/144435005
Flyweight mode https://blog.csdn.net/zhaoxilengfeng/article/details/144458629
03 Golang 24 design patterns - behavioral patterns
Behavioral pattern (Behavioral pattern) mainly focuses on the distribution of responsibilities and communication methods between objects. The core idea of behavioral patterns is to better realize the functions of the system and reduce the coupling between objects by defining the interaction between objects.
Chain of Responsibility Model Chain of Responsibility
Is a behavioral design pattern that allows multiple objects the opportunity to handle requests, thereby avoiding coupling between the sender and receiver of the request. The chain of responsibility pattern connects these objects into a chain and passes the request along this chain until an object handles it.
Core idea:
- Decouple the request sender and receiver: The sender of the request does not need to know which object handles the request, and only needs to send the request to the chain.
- Dynamic combination processing logic: Processors can be dynamically combined, and the processing order can be flexibly adjusted or new processors added.
- Each processor only cares about its own responsibilities: each processor only processes requests that it can handle, and requests that cannot be processed will be passed to the next processor.
Applicable scenarios:
- When a request needs to be processed by multiple objects, but it is not sure which object will handle it.
- When it is necessary to dynamically specify the object that handles the request.
- When one wishes to avoid tight coupling between request sender and receiver.
Practical application scenarios:
- Middleware
- Approval process
Implement the middleware function of gin. The middleware can process requests by itself, intercept them, and release them.
package main
import (
"fmt"
"net/http"
)
// Context 模拟 Gin 的上下文
type Context struct {
Request *http.Request
Writer http.ResponseWriter
handlers []HandlerFunc // 责任链中的处理函数
index int // 当前执行的处理函数索引
}
// HandlerFunc 定义处理函数类型
type HandlerFunc func(c *Context)
// Next 调用责任链中的下一个处理函数
func (c *Context) Next() {
c.index++
if c.index < len(c.handlers) {
c.handlers[c.index](c)
}
}
// Abort 终止责任链的执行
func (c *Context) Abort() {
c.index = len(c.handlers) // 直接跳到末尾,不再执行后续处理函数
}
// Engine 模拟 Gin 的引擎
type Engine struct {
handlers []HandlerFunc // 全局中间件和责任链
}
// Use 添加中间件到责任链
func (e *Engine) Use(middleware HandlerFunc) {
e.handlers = append(e.handlers, middleware)
}
// ServeHTTP 实现 http.Handler 接口
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := &Context{
Request: r,
Writer: w,
handlers: e.handlers,
index: -1,
}
c.Next() // 开始执行责任链
}
// LoggingMiddleware 示例中间件 1:日志记录
func LoggingMiddleware(c *Context) {
fmt.Printf("Request: %s %s\n", c.Request.Method, c.Request.URL.Path)
c.Next() // 传递给下一个中间件
}
// AuthMiddleware 示例中间件 2:认证检查
func AuthMiddleware(c *Context) {
token := c.Request.Header.Get("Authorization")
if token != "valid-token" {
c.Writer.WriteHeader(http.StatusUnauthorized)
c.Writer.Write([]byte("Unauthorized"))
c.Abort() // 终止责任链
return
}
c.Next() // 传递给下一个中间件
}
// HelloHandler 示例中间件 3:请求处理
func HelloHandler(c *Context) {
c.Writer.WriteHeader(http.StatusOK)
c.Writer.Write([]byte("Hello, World!"))
}
func main() {
// 创建引擎
engine := &Engine{}
// 添加中间件到责任链
engine.Use(LoggingMiddleware)
engine.Use(AuthMiddleware)
engine.Use(HelloHandler)
// 启动 HTTP 服务器
fmt.Println("Server is running on :8080")
http.ListenAndServe(":8080", engine)
}
The chain of responsibility pattern is a powerful behavioral design pattern, especially suitable for scenarios where you need to decouple the sender and receiver of a request, support multiple handlers, or dynamically add and remove handlers.
By introducing the Chain of Responsibility pattern, a request can be passed to multiple handlers until one handler is able to handle the request. This not only improves the flexibility and maintainability of the code, but also enhances the scalability of the system.
Command mode Command
It encapsulates requests as an object, allowing you to parameterize clients with different requests, and supports request queuing, logging, undoing operations and other functions.
Core idea:
- Encapsulate requests as objects: Encapsulate each request (such as method call) into an independent object.
- Decouple the sender and receiver of the request: the sender does not need to know the specific implementation of the receiver, and only needs to execute the request through the command object.
- Support extension: New commands can be easily added without modifying existing code.
Example: Suppose we have a task queue system that handles tasks submitted by users. Each task is a command object, and the task queue executes these commands in sequence. Tasks can be simple operations (such as printing messages) or complex operations (such as sending emails, processing data, etc.)
package main
import (
"fmt"
"time"
)
// Command 定义命令接口
type Command interface {
Execute()
}
// PrintCommand 是具体命令,表示打印消息
type PrintCommand struct {
message string
}
func (c *PrintCommand) Execute() {
fmt.Println("Executing PrintCommand:", c.message)
}
// EmailCommand 是具体命令,表示发送邮件
type EmailCommand struct {
to string
subject string
body string
}
func (c *EmailCommand) Execute() {
fmt.Printf("Executing EmailCommand: Sending email to %s\n", c.to)
fmt.Printf("Subject: %s\n", c.subject)
fmt.Printf("Body: %s\n", c.body)
}
// TaskQueue 是任务队列,用于存储和执行命令
type TaskQueue struct {
commands []Command
}
func (tq *TaskQueue) AddCommand(cmd Command) {
tq.commands = append(tq.commands, cmd)
}
func (tq *TaskQueue) ProcessCommands() {
for _, cmd := range tq.commands {
cmd.Execute()
time.Sleep(1 * time.Second) // 模拟任务执行的时间
}
tq.commands = nil // 清空任务队列
}
func main() {
// 创建任务队列
taskQueue := &TaskQueue{}
// 添加任务到队列
taskQueue.AddCommand(&PrintCommand{message: "Hello, World!"})
taskQueue.AddCommand(&EmailCommand{
to: "user@example.com",
subject: "Welcome",
body: "Thank you for signing up!",
})
taskQueue.AddCommand(&PrintCommand{message: "Task queue is running..."})
// 处理任务队列
fmt.Println("Processing task queue:")
taskQueue.ProcessCommands()
// 添加更多任务
taskQueue.AddCommand(&PrintCommand{message: "Another task"})
taskQueue.AddCommand(&EmailCommand{
to: "admin@example.com",
subject: "Report",
body: "Here is the daily report.",
})
// 再次处理任务队列
fmt.Println("\nProcessing task queue again:")
taskQueue.ProcessCommands()
}
Interpreter mode Interpreter
It defines a syntactic representation of a language and provides an interpreter to interpret this syntax. The interpreter mode is usually used to handle scenarios such as programming languages, query languages, rule engines, etc.
Core idea:
- Define grammar rules: express the grammar rules of the language as an abstract syntax tree (AST).
- Interpretation and execution: Traverse the abstract syntax tree through the interpreter and perform corresponding operations.
Abstract syntax tree
Abstract Syntax Tree (AST) is a core concept in compilers and interpreters. It is a tree data structure used to represent the syntactic structure of source code. The reason why AST is called "abstract syntax tree" is that it abstracts away some specific details in the source code and only retains the logical structure of the program.
Why is it called "Abstract Syntax Tree"?
- Abstract:
- AST does not contain all the details in the source code, such as brackets, semicolons, spaces, etc. It only focuses on the logical structure of the program.
- For example, the AST of the expression
2 * (3 + 4)will abstract away the parentheses and only retain the hierarchical relationship between operators and operands.
- Syntax:
- AST represents the syntactic structure of the source code, not the semantics (that is, the meaning of the program).
- For example, AST can represent the syntactic structure of a
ifstatement, but will not explain the specific behavior of theifstatement.
- Tree:
- AST is a tree data structure, each node represents a grammatical structure (such as expression, statement, function, etc.).
- The hierarchical structure of the tree reflects the nested relationship of the source code.
For example
if x > 0 {
print("Positive")
} else {
print("Non-positive")
}
The corresponding AST is
IfStatement
├── Condition: BinaryExpression
│ ├── Left: Identifier (x)
│ ├── Operator: >
│ └── Right: Number (0)
├── ThenBlock: BlockStatement
│ └── Expression: CallExpression
│ ├── Function: Identifier (print)
│ └── Arguments: StringLiteral ("Positive")
└── ElseBlock: BlockStatement
└── Expression: CallExpression
├── Function: Identifier (print)
└── Arguments: StringLiteral ("Non-positive")
There are still many applications of the interpreter mode.
- Database query engine:
- Query parsing and execution of databases such as MySQL and PostgreSQL.
- Rule engine:
- Such as business rules engine, used to parse and execute rules.
- Template engine:
- Such as Go's
text/template, used to parse and execute templates.
- Such as Go's
- Mathematical expression calculation:
- Like calculator app for parsing and calculating mathematical expressions.
Take the template string in the Go language as an example:
package main
import (
"os"
"text/template"
)
func main() {
// 定义模板字符串
const tmpl = `Hello, {{.Name}}! You are {{.Age}} years old.`
// 解析模板
t, err := template.New("example").Parse(tmpl)
if err != nil {
panic(err)
}
// 定义数据
data := struct {
Name string
Age int
}{
Name: "Alice",
Age: 25,
}
// 执行模板并输出结果
err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
This is an application of the interpreter mode. We need to understand the internal principles. We can create such a template string parser by ourselves.
package main
import (
"fmt"
"strings"
)
// Context 定义上下文,存储模板数据
type Context struct {
Data map[string]interface{}
}
// Expression 定义抽象表达式接口
type Expression interface {
Interpret(ctx *Context) string
}
// TextExpression 是文本表达式,表示普通文本
type TextExpression struct {
text string
}
func (t *TextExpression) Interpret(ctx *Context) string {
return t.text
}
// VariableExpression 是变量表达式,表示变量替换
type VariableExpression struct {
key string
}
func (v *VariableExpression) Interpret(ctx *Context) string {
value, ok := ctx.Data[v.key]
if !ok {
return ""
}
return fmt.Sprintf("%v", value)
}
// Template 是模板,包含多个表达式
type Template struct {
expressions []Expression
}
func (t *Template) Interpret(ctx *Context) string {
var result strings.Builder
for _, expr := range t.expressions {
result.WriteString(expr.Interpret(ctx))
}
return result.String()
}
// ParseTemplate 解析模板字符串并构建抽象语法树
func ParseTemplate(tmpl string) *Template {
template := &Template{}
start := 0
for {
// 查找变量表达式的起始位置
startVar := strings.Index(tmpl[start:], "{{")
if startVar == -1 {
// 如果没有变量表达式,剩下的都是普通文本
template.expressions = append(template.expressions, &TextExpression{text: tmpl[start:]})
break
}
// 添加普通文本
template.expressions = append(template.expressions, &TextExpression{text: tmpl[start : start+startVar]})
// 查找变量表达式的结束位置
endVar := strings.Index(tmpl[start+startVar:], "}}")
if endVar == -1 {
// 如果没有结束符,直接退出
break
}
// 解析变量表达式
key := strings.TrimSpace(tmpl[start+startVar+2 : start+startVar+endVar])
template.expressions = append(template.expressions, &VariableExpression{key: key})
// 更新起始位置
start = start + startVar + endVar + 2
}
return template
}
func main() {
// 定义模板字符串
tmpl := "Hello, {{Name}}! You are {{Age}} years old."
// 解析模板并构建抽象语法树
template := ParseTemplate(tmpl)
// 定义上下文数据
ctx := &Context{
Data: map[string]interface{}{
"Name": "Alice",
"Age": 25,
},
}
// 解释执行模板并输出结果
result := template.Interpret(ctx)
fmt.Println(result) // 输出: Hello, Alice! You are 25 years old.
}
Iterator pattern Iterator
It provides a way to sequentially access the individual elements of an aggregate object without exposing the object's internal representation. The core idea of the iterator pattern is to separate the traversal logic from the aggregate object, so that the aggregate object and the traversal logic can change independently.
Practical application scenarios
- Collection class library:
- Collection types such as Go's
sliceandmapcan provide a unified traversal interface through the iterator mode.
- Collection types such as Go's
- Database query results:
- Database query results can be encapsulated as an aggregate object and provide an iterator to traverse the query results.
- File system traversal:
- Directories and files in the file system can be encapsulated as an aggregate object and provide an iterator to traverse the file system.
- Tree structure traversal:
- Tree structures (such as binary trees, multi-trees) can provide multiple traversal methods (such as depth-first, breadth-first).
Suppose we have a collection class BookCollection that contains multiple books. We need to implement an iterator to traverse this collection.
package main
import "fmt"
// Book 定义书籍结构体
type Book struct {
Title string
Author string
}
// Iterator 定义迭代器接口
type Iterator interface {
HasNext() bool
Next() *Book
}
// BookIterator 是具体迭代器
type BookIterator struct {
books []*Book
position int
}
func (b *BookIterator) HasNext() bool {
return b.position < len(b.books)
}
func (b *BookIterator) Next() *Book {
if b.HasNext() {
book := b.books[b.position]
b.position++
return book
}
return nil
}
// Aggregate 定义聚合接口
type Aggregate interface {
CreateIterator() Iterator
}
// BookCollection 是具体聚合
type BookCollection struct {
books []*Book
}
func (b *BookCollection) CreateIterator() Iterator {
return &BookIterator{books: b.books}
}
func main() {
// 创建书籍集合
collection := &BookCollection{
books: []*Book{
{Title: "The Go Programming Language", Author: "Alan A. A. Donovan"},
{Title: "Design Patterns", Author: "Erich Gamma"},
{Title: "Clean Code", Author: "Robert C. Martin"},
},
}
// 创建迭代器
iterator := collection.CreateIterator()
// 遍历集合
for iterator.HasNext() {
book := iterator.Next()
fmt.Printf("Title: %s, Author: %s\n", book.Title, book.Author)
}
}
Mediator Mode Mediator
It encapsulates the interaction between a set of objects by introducing a mediator object. The core idea of the mediator pattern is to concentrate the complex interactions between objects into a mediator object, thereby reducing the direct coupling between objects.
Suppose we have a chat room system where users (colleague classes) send messages through the chat room (mediator). Users do not communicate directly with each other, but forward messages through chat rooms.
package main
import "fmt"
// Mediator 定义中介者接口
type Mediator interface {
SendMessage(message string, sender Colleague)
}
// ChatRoom 是具体中介者
type ChatRoom struct {
users []Colleague
}
func (c *ChatRoom) Register(user Colleague) {
c.users = append(c.users, user)
}
func (c *ChatRoom) SendMessage(message string, sender Colleague) {
for _, user := range c.users {
if user != sender {
user.Receive(message)
}
}
}
// Colleague 定义同事类接口
type Colleague interface {
Send(message string)
Receive(message string)
}
// User 是具体同事类
type User struct {
name string
mediator Mediator
}
func (u *User) Send(message string) {
fmt.Printf("%s sends: %s\n", u.name, message)
u.mediator.SendMessage(message, u)
}
func (u *User) Receive(message string) {
fmt.Printf("%s receives: %s\n", u.name, message)
}
func main() {
// 创建中介者
chatRoom := &ChatRoom{}
// 创建用户
alice := &User{name: "Alice", mediator: chatRoom}
bob := &User{name: "Bob", mediator: chatRoom}
charlie := &User{name: "Charlie", mediator: chatRoom}
// 注册用户到聊天室
chatRoom.Register(alice)
chatRoom.Register(bob)
chatRoom.Register(charlie)
// 用户发送消息
alice.Send("Hello, everyone!")
bob.Send("Hi, Alice!")
charlie.Send("Hey, Bob!")
}
Advantages of the intermediary model
- Reduce coupling:
- Objects do not communicate directly, but interact through intermediaries, reducing the coupling between objects.
- Centralized control:
- Centralize the interaction logic between objects into the mediator to facilitate maintenance and expansion.
- Simplify object responsibilities:
- Each object only needs to pay attention to its own behavior and does not need to know the existence of other objects.
Memento Mode Memento
It allows the internal state of an object to be captured and externalized without breaking encapsulation, so that the object can be restored to its previous state later. The core idea of the memo pattern is to save the state of an object into a memo object and restore the state from the memo when needed.
package main
import "fmt"
// Memento 定义备忘录接口
type Memento interface {
GetState() string
}
// TextMemento 是具体备忘录
type TextMemento struct {
state string
}
func (t *TextMemento) GetState() string {
return t.state
}
// Originator 是原发器
type Originator struct {
state string
}
func (o *Originator) SetState(state string) {
o.state = state
}
func (o *Originator) GetState() string {
return o.state
}
func (o *Originator) CreateMemento() Memento {
return &TextMemento{state: o.state}
}
func (o *Originator) RestoreMemento(m Memento) {
o.state = m.GetState()
}
// Caretaker 是管理者
type Caretaker struct {
mementos []Memento
}
func (c *Caretaker) AddMemento(m Memento) {
c.mementos = append(c.mementos, m)
}
func (c *Caretaker) GetMemento(index int) Memento {
if index < len(c.mementos) {
return c.mementos[index]
}
return nil
}
func main() {
// 创建原发器
editor := &Originator{}
// 创建管理者
caretaker := &Caretaker{}
// 编辑文本并保存状态
editor.SetState("State 1")
caretaker.AddMemento(editor.CreateMemento()) // 创建一个备忘录对象,保存当前状态。
editor.SetState("State 2")
caretaker.AddMemento(editor.CreateMemento())
editor.SetState("State 3")
caretaker.AddMemento(editor.CreateMemento())
fmt.Println(editor.GetState()) // 这个时候的状态已经是 State 3
// 恢复到之前的状态
editor.RestoreMemento(caretaker.GetMemento(1))
fmt.Println("Restored State:", editor.GetState()) // 输出: Restored State: State 2
editor.RestoreMemento(caretaker.GetMemento(0))
fmt.Println("Restored State:", editor.GetState()) // 输出: Restored State: State 1
}
This method is very suitable for scenarios that need to support undo operations or state management, such as text editors, game archives, transaction rollbacks, etc. In the Go language, the memo pattern can be implemented through a combination of interfaces and structures. The code is concise and easy to extend.
Observer Pattern Observer
It defines one-to-many dependencies between objects. When the state of an object (observer) changes, all objects (observers) that depend on it are notified and automatically updated.
The core idea of the observer pattern is to decouple the observed and the observer so that they can change independently.
Suppose we have a weather station (observer) that notifies multiple display devices (observers) to update the display content when the weather data is updated.
package main
import "fmt"
// Observer 定义观察者接口
type Observer interface {
Update(temperature float64, humidity float64, pressure float64)
}
// Subject 定义被观察者接口
type Subject interface {
RegisterObserver(o Observer)
RemoveObserver(o Observer)
NotifyObservers()
}
// WeatherData 是具体被观察者
type WeatherData struct {
observers []Observer
temperature float64
humidity float64
pressure float64
}
func (w *WeatherData) RegisterObserver(o Observer) {
w.observers = append(w.observers, o)
}
func (w *WeatherData) RemoveObserver(o Observer) {
for i, observer := range w.observers {
if observer == o {
w.observers = append(w.observers[:i], w.observers[i+1:]...)
break
}
}
}
func (w *WeatherData) NotifyObservers() {
for _, observer := range w.observers {
observer.Update(w.temperature, w.humidity, w.pressure)
}
}
func (w *WeatherData) SetMeasurements(temperature float64, humidity float64, pressure float64) {
w.temperature = temperature
w.humidity = humidity
w.pressure = pressure
w.NotifyObservers()
}
// DisplayDevice 是具体观察者
type DisplayDevice struct {
name string
}
func (d *DisplayDevice) Update(temperature float64, humidity float64, pressure float64) {
fmt.Printf("%s: Temperature=%.2f, Humidity=%.2f, Pressure=%.2f\n", d.name, temperature, humidity, pressure)
}
func main() {
// 创建被观察者
weatherData := &WeatherData{}
// 创建观察者
display1 := &DisplayDevice{name: "Display 1"}
display2 := &DisplayDevice{name: "Display 2"}
// 注册观察者
weatherData.RegisterObserver(display1)
weatherData.RegisterObserver(display2)
// 更新天气数据并通知观察者
weatherData.SetMeasurements(25.0, 65.0, 1013.0)
weatherData.SetMeasurements(26.5, 70.0, 1012.5)
// 移除一个观察者
weatherData.RemoveObserver(display1)
// 再次更新天气数据
weatherData.SetMeasurements(27.0, 68.0, 1011.0)
}
Advantages of Observer Pattern
- Decoupling:
- The observed and the observer are loosely coupled and they can change independently.
- Support dynamic registration and removal of observers:
- Observers can be dynamically registered and removed at runtime.
- Comply with the opening and closing principle:
- When adding an observer, there is no need to modify the code of the observed.
State mode State
It allows an object to change its behavior when its internal state changes. The core idea of the state pattern is to encapsulate the state of an object into an independent class and delegate the object's behavior to the current state object.
Through the state pattern, complex conditional logic can be dispersed into multiple state classes, making the code clearer and easier to maintain.
package main
import "fmt"
// State 定义状态接口
type State interface {
PressSwitch(context *Context)
}
// Context 是上下文
type Context struct {
state State
}
func (c *Context) SetState(state State) {
c.state = state
}
func (c *Context) PressSwitch() {
c.state.PressSwitch(c)
}
// OnState 是具体状态:开
type OnState struct{}
func (o *OnState) PressSwitch(context *Context) {
fmt.Println("Turning the light off...")
context.SetState(&OffState{})
}
// OffState 是具体状态:关
type OffState struct{}
func (o *OffState) PressSwitch(context *Context) {
fmt.Println("Turning the light on...")
context.SetState(&OnState{})
}
func main() {
// 创建上下文并设置初始状态
context := &Context{state: &OffState{}}
// 按下开关
context.PressSwitch() // 输出: Turning the light on...
context.PressSwitch() // 输出: Turning the light off...
context.PressSwitch() // 输出: Turning the light on...
}
Advantages of State Pattern
- Clear state transition logic:
- Disperse state transition logic into various state classes to avoid complex conditional statements.
- Comply with the opening and closing principle:
- When adding a new state, you only need to add a new state class without modifying the existing code.
- Easy to expand:
- New states and behaviors can be easily added.
Strategy Mode Strategy
It defines a series of algorithms and encapsulates each algorithm so that they can be interchanged. The core idea of the strategy pattern is to separate the use of the algorithm from the implementation of the algorithm, so that the algorithm can change independently of the client.
Strategy pattern allows you to dynamically select algorithms at runtime without modifying client code.
Suppose we have a payment system that supports multiple payment methods (such as credit card payment, Alipay payment, WeChat payment, etc.). We can use the strategy pattern to implement payment method selection.
package main
import "fmt"
// PaymentStrategy 定义策略接口
type PaymentStrategy interface {
Pay(amount float64)
}
// CreditCardPayment 是具体策略:信用卡支付
type CreditCardPayment struct{}
func (c *CreditCardPayment) Pay(amount float64) {
fmt.Printf("Paying %.2f using Credit Card\n", amount)
}
// AlipayPayment 是具体策略:支付宝支付
type AlipayPayment struct{}
func (a *AlipayPayment) Pay(amount float64) {
fmt.Printf("Paying %.2f using Alipay\n", amount)
}
// WechatPayment 是具体策略:微信支付
type WechatPayment struct{}
func (w *WechatPayment) Pay(amount float64) {
fmt.Printf("Paying %.2f using Wechat Pay\n", amount)
}
// PaymentContext 是上下文
type PaymentContext struct {
strategy PaymentStrategy
}
func (p *PaymentContext) SetStrategy(strategy PaymentStrategy) {
p.strategy = strategy
}
func (p *PaymentContext) ExecutePayment(amount float64) {
p.strategy.Pay(amount)
}
func main() {
// 创建上下文
context := &PaymentContext{}
// 使用信用卡支付
context.SetStrategy(&CreditCardPayment{})
context.ExecutePayment(100.0) // 输出: Paying 100.00 using Credit Card
// 使用支付宝支付
context.SetStrategy(&AlipayPayment{})
context.ExecutePayment(200.0) // 输出: Paying 200.00 using Alipay
// 使用微信支付
context.SetStrategy(&WechatPayment{})
context.ExecutePayment(300.0) // 输出: Paying 300.00 using Wechat Pay
}
Advantages of Strategy Pattern
- Decoupling:
- Separate the use of the algorithm from the implementation of the algorithm so that the algorithm can change independently of the client.
- Easy to expand:
- When adding a new algorithm, you only need to add a new strategy class without modifying the existing code.
- Dynamic selection algorithm:
- Algorithms can be selected dynamically at runtime without modifying client code.
Practical application scenarios
- Payment system:
- Supports multiple payment methods as shown in the example.
- Sorting algorithm:
- Supports multiple sorting algorithms (such as quick sort, merge sort, bubble sort, etc.).
- Compression algorithm:
- Supports multiple compression algorithms (such as ZIP, RAR, 7z, etc.).
- Routing algorithm:
- Supports multiple routing algorithms (such as shortest path, fastest path, least charged path, etc.).
Template Method Pattern Template Method
It defines the skeleton of an algorithm and defers certain steps to subclasses. The core idea of the template method pattern is to put the common part of the algorithm in the parent class, and leave the variable part to the subclass for implementation.
Through the template method pattern, you can avoid code duplication and ensure that the structure of the algorithm remains unchanged.
Suppose we have a beverage making system that supports making coffee and tea. The coffee and tea making processes have some common steps (such as boiling water, pouring into cups), and some different steps (such as brewing coffee, making tea).
package main
import "fmt"
// Beverage 是抽象类,定义饮料制作的模板方法
type Beverage interface {
BoilWater() // 烧水
Brew() // 冲泡
PourInCup() // 倒入杯子
AddCondiments() // 添加调料
WantCondiments() bool // 是否添加调料(钩子方法)
}
// MakeBeverage 是模板方法
func MakeBeverage(b Beverage) {
b.BoilWater()
b.Brew()
b.PourInCup()
if b.WantCondiments() {
b.AddCondiments()
}
}
// Coffee 是具体类:咖啡
type Coffee struct{}
func (c *Coffee) BoilWater() {
fmt.Println("Boiling water")
}
func (c *Coffee) Brew() {
fmt.Println("Brewing coffee")
}
func (c *Coffee) PourInCup() {
fmt.Println("Pouring coffee into cup")
}
func (c *Coffee) AddCondiments() {
fmt.Println("Adding sugar and milk")
}
func (c *Coffee) WantCondiments() bool {
return true
}
// Tea 是具体类:茶
type Tea struct{}
func (t *Tea) BoilWater() {
fmt.Println("Boiling water")
}
func (t *Tea) Brew() {
fmt.Println("Steeping tea")
}
func (t *Tea) PourInCup() {
fmt.Println("Pouring tea into cup")
}
func (t *Tea) AddCondiments() {
fmt.Println("Adding lemon")
}
func (t *Tea) WantCondiments() bool {
return false
}
func main() {
// 制作咖啡
fmt.Println("Making coffee:")
coffee := &Coffee{}
MakeBeverage(coffee)
// 制作茶
fmt.Println("\nMaking tea:")
tea := &Tea{}
MakeBeverage(tea)
}
Advantages of Template Method Pattern
- Code reuse:
- Put the common parts of the algorithm in the parent class to avoid code duplication.
- Scalability:
- When adding a new subclass, you only need to implement abstract methods without modifying the code of the parent class.
- Control algorithm structure:
- The parent class controls the structure of the algorithm, ensuring that the steps of the algorithm are not changed by subclasses.
Practical application scenarios
- Frame design:
- Such as the request processing process in the web framework (initialization, processing requests, returning responses, etc.).
- Workflow engine:
- Such as order processing process (create order, pay order, ship order, etc.).
- Testing framework:
- Such as the execution process of test cases (initialization, test execution, resource cleanup, etc.).
- Game development:
- Such as the behavior process of game characters (movement, attack, defense, etc.).
Visitor mode Visitor
It allows you to separate algorithms from object structures. The core idea of the visitor pattern is to separate operations (algorithms) from the object structure, so that new operations can be defined without modifying the object structure.
Through the visitor pattern, you can decouple the elements of an object structure from the operations that act on these elements, so that the operations can change independently.
Suppose we have a Document Object Model (DOM) containing various elements (such as text, pictures, tables, etc.). We need to perform different operations on these elements (like export to PDF, export to HTML, etc.).
package main
import "fmt"
// Visitor 定义访问者接口
type Visitor interface {
VisitText(text *Text)
VisitImage(image *Image)
VisitTable(table *Table)
}
// Element 定义元素接口
type Element interface {
Accept(visitor Visitor)
}
// Text 是具体元素:文本
type Text struct {
content string
}
func (t *Text) Accept(visitor Visitor) {
visitor.VisitText(t)
}
// Image 是具体元素:图片
type Image struct {
src string
}
func (i *Image) Accept(visitor Visitor) {
visitor.VisitImage(i)
}
// Table 是具体元素:表格
type Table struct {
rows int
cols int
}
func (t *Table) Accept(visitor Visitor) {
visitor.VisitTable(t)
}
// PDFExportVisitor 是具体访问者:导出为 PDF
type PDFExportVisitor struct{}
func (p *PDFExportVisitor) VisitText(text *Text) {
fmt.Printf("Exporting text to PDF: %s\n", text.content)
}
func (p *PDFExportVisitor) VisitImage(image *Image) {
fmt.Printf("Exporting image to PDF: %s\n", image.src)
}
func (p *PDFExportVisitor) VisitTable(table *Table) {
fmt.Printf("Exporting table to PDF: %d rows, %d cols\n", table.rows, table.cols)
}
// HTMLExportVisitor 是具体访问者:导出为 HTML
type HTMLExportVisitor struct{}
func (h *HTMLExportVisitor) VisitText(text *Text) {
fmt.Printf("Exporting text to HTML: %s\n", text.content)
}
func (h *HTMLExportVisitor) VisitImage(image *Image) {
fmt.Printf("Exporting image to HTML: %s\n", image.src)
}
func (h *HTMLExportVisitor) VisitTable(table *Table) {
fmt.Printf("Exporting table to HTML: %d rows, %d cols\n", table.rows, table.cols)
}
// Document 是对象结构
type Document struct {
elements []Element
}
func (d *Document) AddElement(element Element) {
d.elements = append(d.elements, element)
}
func (d *Document) Accept(visitor Visitor) {
for _, element := range d.elements {
element.Accept(visitor)
}
}
func main() {
// 创建文档对象
document := &Document{}
// 添加元素
document.AddElement(&Text{content: "Hello, World!"})
document.AddElement(&Image{src: "image.png"})
document.AddElement(&Table{rows: 3, cols: 2})
// 创建访问者
pdfVisitor := &PDFExportVisitor{}
htmlVisitor := &HTMLExportVisitor{}
// 导出为 PDF
fmt.Println("Exporting to PDF:")
document.Accept(pdfVisitor)
// 导出为 HTML
fmt.Println("\nExporting to HTML:")
document.Accept(htmlVisitor)
}
Advantages of Visitor Pattern
- Decoupling:
- Separate operations from object structures so operations can change independently.
- Scalability:
- When adding new operations, you only need to add new visitors without modifying the object structure.
- Comply with the opening and closing principle:
- The object structure is open for extension and closed for modification.