avatar

go语言实现常见的设计模式


1. 单例模式 (Singleton Pattern)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

 1package main
 2
 3import (
 4	"fmt"
 5	"sync"
 6)
 7
 8type Singleton struct {
 9}
10
11var (
12	instance *Singleton
13	once     sync.Once
14)
15
16func GetInstance() *Singleton {
17	once.Do(func() {
18		instance = &Singleton{}
19	})
20	return instance
21}
22
23func main() {
24	s1 := GetInstance()
25	s2 := GetInstance()
26
27	if s1 == s2 {
28		fmt.Println("Both instances are the same.")
29	} else {
30		fmt.Println("Instances are different.")
31	}
32}

2. 工厂模式 (Factory Pattern)

工厂模式提供了一种创建对象的方式,隐藏了实例化对象的复杂逻辑。

 1package main
 2
 3import "fmt"
 4
 5// Product 是定义了产品接口
 6type Product interface {
 7	Use() string
 8}
 9
10// ConcreteProductA 是具体产品A的实现
11type ConcreteProductA struct{}
12
13func (p *ConcreteProductA) Use() string {
14	return "Using ConcreteProductA"
15}
16
17// ConcreteProductB 是具体产品B的实现
18type ConcreteProductB struct{}
19
20func (p *ConcreteProductB) Use() string {
21	return "Using ConcreteProductB"
22}
23
24// Factory 是工厂结构体
25type Factory struct{}
26
27func (f *Factory) CreateProduct(productType string) Product {
28	switch productType {
29	case "A":
30		return &ConcreteProductA{}
31	case "B":
32		return &ConcreteProductB{}
33	default:
34		return nil
35	}
36}
37
38func main() {
39	factory := &Factory{}
40
41	productA := factory.CreateProduct("A")
42	fmt.Println(productA.Use())
43
44	productB := factory.CreateProduct("B")
45	fmt.Println(productB.Use())
46}

3. 观察者模式 (Observer Pattern)

观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖对象都会收到通知并自动更新。

 1package main
 2
 3import "fmt"
 4
 5// Observer 是观察者接口
 6type Observer interface {
 7	Update(data string)
 8}
 9
10// Subject 是主题接口
11type Subject interface {
12	Register(observer Observer)
13	Deregister(observer Observer)
14	Notify()
15}
16
17// ConcreteObserver 是具体的观察者实现
18type ConcreteObserver struct {
19	name string
20}
21
22func (o *ConcreteObserver) Update(data string) {
23	fmt.Printf("%s received data: %s\n", o.name, data)
24}
25
26// ConcreteSubject 是具体的主题实现
27type ConcreteSubject struct {
28	observers []Observer
29	data      string
30}
31
32func (s *ConcreteSubject) Register(observer Observer) {
33	s.observers = append(s.observers, observer)
34}
35
36func (s *ConcreteSubject) Deregister(observer Observer) {
37	for i, o := range s.observers {
38		if o == observer {
39			s.observers = append(s.observers[:i], s.observers[i+1:]...)
40			break
41		}
42	}
43}
44
45func (s *ConcreteSubject) Notify() {
46	for _, observer := range s.observers {
47		observer.Update(s.data)
48	}
49}
50
51func (s *ConcreteSubject) SetData(data string) {
52	s.data = data
53	s.Notify()
54}
55
56func main() {
57	subject := &ConcreteSubject{}
58
59	observer1 := &ConcreteObserver{name: "Observer1"}
60	observer2 := &ConcreteObserver{name: "Observer2"}
61
62	subject.Register(observer1)
63	subject.Register(observer2)
64
65	subject.SetData("New Data")
66}

4. 策略模式 (Strategy Pattern)

策略模式定义一系列算法,将每个算法封装起来,并使它们可以互换。

 1package main
 2
 3import "fmt"
 4
 5// Strategy 是策略接口
 6type Strategy interface {
 7	Execute(a, b int) int
 8}
 9
10// ConcreteStrategyAdd 是加法策略的实现
11type ConcreteStrategyAdd struct{}
12
13func (s *ConcreteStrategyAdd) Execute(a, b int) int {
14	return a + b
15}
16
17// ConcreteStrategySubtract 是减法策略的实现
18type ConcreteStrategySubtract struct{}
19
20func (s *ConcreteStrategySubtract) Execute(a, b int) int {
21	return a - b
22}
23
24// Context 是上下文,持有一个策略的引用
25type Context struct {
26	strategy Strategy
27}
28
29func (c *Context) SetStrategy(strategy Strategy) {
30	c.strategy = strategy
31}
32
33func (c *Context) ExecuteStrategy(a, b int) int {
34	return c.strategy.Execute(a, b)
35}
36
37func main() {
38	context := &Context{}
39
40	context.SetStrategy(&ConcreteStrategyAdd{})
41	fmt.Println("Add:", context.ExecuteStrategy(5, 3))
42
43	context.SetStrategy(&ConcreteStrategySubtract{})
44	fmt.Println("Subtract:", context.ExecuteStrategy(5, 3))
45}

评论列表:

暂无评论 😭