23种常见设计模式

为了更清晰地展示这23种设计模式,我将为每种模式提供 基本概念结构示例。为了便于理解,每种模式我都会简要描述它的作用、结构及适用的场景,并提供相应的代码示例(尽量简洁明了)。



一、创建型模式(Creational Patterns)



1. 单例模式(Singleton Pattern)

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

结构

  • Singleton:类本身,确保类只会创建一个实例。
  • Client:客户端通过getInstance()方法获取唯一实例。

示例(Go语言):

package main

import "fmt"

// Singleton类
type Singleton struct{}

var instance *Singleton

// 获取唯一实例
func GetInstance() *Singleton {
	if instance == nil {
		instance = &Singleton{}
	}
	return instance
}

func main() {
	s1 := GetInstance()
	s2 := GetInstance()

	fmt.Println(s1 == s2) // true,证明只有一个实例
}


2. 工厂方法模式(Factory Method Pattern)

基本概念
定义一个创建对象的接口,但由子类决定实例化哪一个类。

结构

  • Product:产品接口。
  • ConcreteProduct:具体产品类。
  • Creator:工厂类,声明工厂方法。
  • ConcreteCreator:具体工厂类,负责实例化具体的产品。

示例(Go语言):

package main

import "fmt"

// Product接口
type Product interface {
	Use() string
}

// ConcreteProduct
type ConcreteProductA struct{}
func (p *ConcreteProductA) Use() string {
	return "Using Product A"
}

type ConcreteProductB struct{}
func (p *ConcreteProductB) Use() string {
	return "Using Product B"
}

// Creator接口
type Creator interface {
	FactoryMethod() Product
}

// ConcreteCreatorA
type ConcreteCreatorA struct{}
func (c *ConcreteCreatorA) FactoryMethod() Product {
	return &ConcreteProductA{}
}

// ConcreteCreatorB
type ConcreteCreatorB struct{}
func (c *ConcreteCreatorB) FactoryMethod() Product {
	return &ConcreteProductB{}
}

func main() {
	creator := &ConcreteCreatorA{}
	product := creator.FactoryMethod()
	fmt.Println(product.Use()) // "Using Product A"
	
	creator = &ConcreteCreatorB{}
	product = creator.FactoryMethod()
	fmt.Println(product.Use()) // "Using Product B"
}


3. 抽象工厂模式(Abstract Factory Pattern)

基本概念
提供一个创建一系列相关或相互依赖对象的接口,而不需要指定具体类。

结构

  • AbstractFactory:抽象工厂,定义一系列的工厂方法。
  • ConcreteFactory:具体工厂,继承抽象工厂,实例化具体产品。
  • AbstractProduct:抽象产品。
  • ConcreteProduct:具体产品。

示例(Go语言):

package main

import "fmt"

// AbstractProduct
type Chair interface {
	Sit() string
}

type Sofa interface {
	Lay() string
}

// ConcreteProduct
type ModernChair struct{}
func (m *ModernChair) Sit() string {
	return "Sitting on Modern Chair"
}

type ModernSofa struct{}
func (m *ModernSofa) Lay() string {
	return "Laying on Modern Sofa"
}

// AbstractFactory
type FurnitureFactory interface {
	FactoryChair() Chair
	FactorySofa() Sofa
}

// ConcreteFactory
type ModernFurnitureFactory struct{}
func (m *ModernFurnitureFactory) FactoryChair() Chair {
	return &ModernChair{}
}
func (m *ModernFurnitureFactory) FactorySofa() Sofa {
	return &ModernSofa{}
}

func main() {
	factory := &ModernFurnitureFactory{}
	chair := factory.FactoryChair()
	sofa := factory.FactorySofa()

	fmt.Println(chair.Sit()) // "Sitting on Modern Chair"
	fmt.Println(sofa.Lay())  // "Laying on Modern Sofa"
}


4. 建造者模式(Builder Pattern)

基本概念
使用多个简单的对象一步步构建成一个复杂的对象。

结构

  • Builder:抽象建造者,定义创建各个部件的接口。
  • ConcreteBuilder:具体建造者,实现创建产品的具体过程。
  • Product:最终产品,包含多个部件。
  • Director:指挥者,负责控制建造过程。

示例(Go语言):

package main

import "fmt"

// Product
type Car struct {
	Engine  string
	Seats   int
	Wheels  int
}

// Builder
type CarBuilder struct {
	car Car
}

func (b *CarBuilder) SetEngine(engine string) *CarBuilder {
	b.car.Engine = engine
	return b
}

func (b *CarBuilder) SetSeats(seats int) *CarBuilder {
	b.car.Seats = seats
	return b
}

func (b *CarBuilder) SetWheels(wheels int) *CarBuilder {
	b.car.Wheels = wheels
	return b
}

func (b *CarBuilder) Build() Car {
	return b.car
}

// Director
type Director struct{}

func (d *Director) Construct(builder *CarBuilder) {
	builder.SetEngine("V8").SetSeats(4).SetWheels(4)
}

func main() {
	builder := &CarBuilder{}
	director := &Director{}
	director.Construct(builder)
	car := builder.Build()

	fmt.Println(car) // {V8 4 4}
}


5. 原型模式(Prototype Pattern)

基本概念
通过复制现有的对象来创建新对象,而不是通过类实例化。

结构

  • Prototype:原型接口,定义复制方法。
  • ConcretePrototype:具体的原型,负责实现复制功能。

示例(Go语言):

package main

import "fmt"

// Prototype接口
type Prototype interface {
	Clone() Prototype
}

// ConcretePrototype
type Product struct {
	Name string
}

func (p *Product) Clone() Prototype {
	return &Product{Name: p.Name}
}

func main() {
	p1 := &Product{Name: "Product1"}
	p2 := p1.Clone().(*Product)
	
	fmt.Println(p1.Name) // "Product1"
	fmt.Println(p2.Name) // "Product1"
}


二、结构型模式(Structural Patterns)



6. 适配器模式(Adapter Pattern)

基本概念
允许将一个类的接口转换成客户端需要的另一个接口。

结构

  • Target:客户端需要的接口。
  • Adapter:适配器类,连接目标接口与被适配对象。
  • Adaptee:被适配的类,具有一个与目标接口不兼容的方法。

示例(Go语言):

package main

import "fmt"

// Target接口
type Target interface {
	Request() string
}

// Adaptee类
type Adaptee struct{}

func (a *Adaptee) SpecificRequest() string {
	return "SpecificRequest"
}

// Adapter类
type Adapter struct {
	adaptee *Adaptee
}

func (a *Adapter) Request() string {
	return a.adaptee.SpecificRequest()
}

func main() {
	adaptee := &Adaptee{}
	adapter := &Adapter{adaptee}
	
	fmt.Println(adapter.Request()) // "SpecificRequest"
}


7. 桥接模式(Bridge Pattern)

基本概念
将抽象部分与实现部分分离,使它们可以独立变化。

结构

  • Abstraction:定义抽象类,包含实现接口。
  • RefinedAbstraction:扩展抽象类,添加一些具体的功能。
  • Implementor:定义接口,描述具体实现。
  • ConcreteImplementor:实现接口,提供具体实现。

示例(Go语言):

package main

import "fmt"

// Implementor接口
type Implementor interface {
	Operation() string
}

// ConcreteImplementor
type ConcreteImplementorA struct{}

func (c *ConcreteImplementorA) Operation() string {
	return "ConcreteImplementorA Operation"
}

type ConcreteImplementorB struct{}

func (c *ConcreteImplementorB) Operation() string {
	return "ConcreteImplementorB Operation"
}

// Abstraction类
type Abstraction struct {
	impl Implementor
}

func (a *Abstraction) Operation() string {
	return a.impl.Operation()
}

func main() {
	implA := &ConcreteImplementorA{}
	implB := &ConcreteImplementorB{}

	abstraction := &Abstraction{impl: implA}
	fmt.Println(abstraction.Operation()) // "ConcreteImplementorA Operation"

	abstraction.impl = implB
	fmt.Println(abstraction.Operation()) // "ConcreteImplementorB Operation"
}

好的,接下来继续展示剩下的设计模式,包括 结构型模式行为型模式。我们继续按照 基本概念结构示例 来进行展示。

8. 组合模式(Composite Pattern)

基本概念
组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。使得客户端可以统一地对待单个对象和对象的组合。

结构

  • Component:抽象组件,定义叶子和容器对象的共同接口。
  • Leaf:叶子节点,表示树的最小元素。
  • Composite:容器节点,包含其他子节点(可以是叶子或其他容器)。

示例(Go语言):

package main

import "fmt"

// Component接口
type Component interface {
	Display() string
}

// Leaf类
type Leaf struct {
	Name string
}

func (l *Leaf) Display() string {
	return "Leaf " + l.Name
}

// Composite类
type Composite struct {
	Children []Component
}

func (c *Composite) Display() string {
	var result string
	for _, child := range c.Children {
		result += child.Display() + " "
	}
	return result
}

func main() {
	leaf1 := &Leaf{Name: "Leaf1"}
	leaf2 := &Leaf{Name: "Leaf2"}
	leaf3 := &Leaf{Name: "Leaf3"}
	
	composite := &Composite{
		Children: []Component{leaf1, leaf2, leaf3},
	}
	
	fmt.Println(composite.Display()) // "Leaf Leaf1 Leaf Leaf2 Leaf Leaf3"
}


9. 装饰器模式(Decorator Pattern)

基本概念
装饰器模式允许通过将行为附加到对象的方式,动态地增加额外的功能。它不改变对象的结构,而是通过包装来扩展对象的行为。

结构

  • Component:接口或抽象类,定义操作。
  • ConcreteComponent:具体类,定义基本的操作。
  • Decorator:装饰器,持有一个Component对象并覆盖它的方法来增加功能。
  • ConcreteDecorator:具体装饰器,附加新的行为。

示例(Go语言):

package main

import "fmt"

// Component接口
type Component interface {
	Operation() string
}

// ConcreteComponent类
type ConcreteComponent struct{}

func (c *ConcreteComponent) Operation() string {
	return "Base Operation"
}

// Decorator类
type Decorator struct {
	component Component
}

func (d *Decorator) Operation() string {
	return d.component.Operation()
}

// ConcreteDecoratorA类
type ConcreteDecoratorA struct {
	Decorator
}

func (d *ConcreteDecoratorA) Operation() string {
	return d.component.Operation() + " + Decorated by A"
}

// ConcreteDecoratorB类
type ConcreteDecoratorB struct {
	Decorator
}

func (d *ConcreteDecoratorB) Operation() string {
	return d.component.Operation() + " + Decorated by B"
}

func main() {
	component := &ConcreteComponent{}
	decoratorA := &ConcreteDecoratorA{Decorator{component}}
	decoratorB := &ConcreteDecoratorB{Decorator{decoratorA}}

	fmt.Println(decoratorB.Operation()) // "Base Operation + Decorated by A + Decorated by B"
}


10. 外观模式(Facade Pattern)

基本概念
外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。它将复杂的系统操作封装在一个简单的接口中,减少了客户端与复杂子系统的交互。

结构

  • Facade:外观类,提供简化的接口。
  • Subsystem classes:子系统类,复杂的操作被封装在这些类中。

示例(Go语言):

package main

import "fmt"

// Subsystem1
type Subsystem1 struct{}
func (s *Subsystem1) Operation1() {
	fmt.Println("Subsystem1: Operation1")
}

// Subsystem2
type Subsystem2 struct{}
func (s *Subsystem2) Operation2() {
	fmt.Println("Subsystem2: Operation2")
}

// Facade
type Facade struct {
	subsystem1 *Subsystem1
	subsystem2 *Subsystem2
}

func (f *Facade) SimplifiedOperation() {
	f.subsystem1.Operation1()
	f.subsystem2.Operation2()
}

func main() {
	facade := &Facade{
		subsystem1: &Subsystem1{},
		subsystem2: &Subsystem2{},
	}
	
	facade.SimplifiedOperation()
	// Output:
	// Subsystem1: Operation1
	// Subsystem2: Operation2
}


11. 享元模式(Flyweight Pattern)

基本概念
享元模式通过共享对象来有效地支持大量细粒度的对象,从而节省内存和提高性能。它将对象的状态分为内外部状态,外部状态可共享。

结构

  • Flyweight:定义对象的接口,提供外部状态。
  • ConcreteFlyweight:具体享元类,负责实现共享的内部状态。
  • FlyweightFactory:享元工厂,管理共享对象。

示例(Go语言):

package main

import "fmt"

// Flyweight接口
type Flyweight interface {
	Operation(extrinsicState string)
}

// ConcreteFlyweight类
type ConcreteFlyweight struct {
	intrinsicState string
}

func (c *ConcreteFlyweight) Operation(extrinsicState string) {
	fmt.Println("Flyweight with intrinsic state:", c.intrinsicState, "and extrinsic state:", extrinsicState)
}

// FlyweightFactory类
type FlyweightFactory struct {
	flyweights map[string]*ConcreteFlyweight
}

func (f *FlyweightFactory) GetFlyweight(key string) *ConcreteFlyweight {
	if _, exists := f.flyweights[key]; !exists {
		f.flyweights[key] = &ConcreteFlyweight{intrinsicState: key}
	}
	return f.flyweights[key]
}

func main() {
	factory := &FlyweightFactory{flyweights: make(map[string]*ConcreteFlyweight)}
	
	flyweightA := factory.GetFlyweight("A")
	flyweightA.Operation("X")
	
	flyweightB := factory.GetFlyweight("B")
	flyweightB.Operation("Y")
	
	flyweightA2 := factory.GetFlyweight("A")
	flyweightA2.Operation("Z")
}


12. 代理模式(Proxy Pattern)

基本概念
代理模式为其他对象提供代理以控制对这个对象的访问。常用于惰性加载、远程对象、权限控制等场景。

结构

  • Subject:公共接口,声明真实对象和代理对象共享的接口。
  • RealSubject:真实对象,执行实际操作。
  • Proxy:代理类,控制访问到真实对象。

示例(Go语言):

package main

import "fmt"

// Subject接口
type Subject interface {
	Request() string
}

// RealSubject类
type RealSubject struct{}

func (r *RealSubject) Request() string {
	return "RealSubject Request"
}

// Proxy类
type Proxy struct {
	realSubject *RealSubject
}

func (p *Proxy) Request() string {
	if p.realSubject == nil {
		p.realSubject = &RealSubject{}
	}
	return "Proxy: " + p.realSubject.Request()
}

func main() {
	proxy := &Proxy{}
	fmt.Println(proxy.Request()) // "Proxy: RealSubject Request"
}


三、行为型模式(Behavioral Patterns)



13. 责任链模式(Chain of Responsibility Pattern)

基本概念
责任链模式使得多个对象都有机会处理请求,从而避免请求发送者和处理者之间的耦合关系。请求沿链传递,直到有对象处理它。

结构

  • Handler:处理请求的接口。
  • ConcreteHandler:具体处理请求的类,处理请求或将其传递给下一个处理者。
  • Client:发起请求。

示例(Go语言):

package main

import "fmt"

// Handler接口
type Handler interface {
	HandleRequest(request string)
	SetNext(handler Handler)
}

// ConcreteHandlerA
type ConcreteHandlerA struct {
	next Handler
}

func (h *ConcreteHandlerA) HandleRequest(request string) {
	if request == "A" {
		fmt.Println("HandlerA: Handling request A")
	} else if h.next != nil {
		h.next.HandleRequest(request)
	}
}

func (h *ConcreteHandlerA) SetNext(handler Handler) {
	h.next = handler
}

// ConcreteHandlerB
type ConcreteHandlerB struct {
	next Handler
}

func (h *ConcreteHandlerB) HandleRequest(request string) {
	if request == "B" {
		fmt.Println("HandlerB: Handling request B")
	} else if h.next != nil {
		h.next.HandleRequest(request)
	}
}

func (h *ConcreteHandlerB) SetNext(handler Handler) {
	h.next = handler
}

func main() {
	handlerA := &ConcreteHandlerA{}
	handlerB := &ConcreteHandlerB{}

	handlerA.SetNext(handlerB)

	handlerA.HandleRequest("B") // "HandlerB: Handling request B"

}


---

继续下一部分,行为型模式的其他设计模式会在下次继续。


14. 命令模式(Command Pattern)

基本概念
命令模式将请求封装成对象,从而使你可以用不同的请求、队列或者日志请求来参数化客户端。它使得你能够撤销操作,甚至支持将请求存储并在之后的某个时刻执行。

结构

  • Command:命令接口,声明执行命令的接口。
  • ConcreteCommand:具体命令类,负责实现命令的执行。
  • Invoker:调用者,发出请求。
  • Receiver:接收者,实际执行操作。

示例(Go语言):

package main

import "fmt"

// Command接口
type Command interface {
	Execute()
}

// Receiver类
type Light struct{}

func (l *Light) TurnOn() {
	fmt.Println("Light is ON")
}

func (l *Light) TurnOff() {
	fmt.Println("Light is OFF")
}

// ConcreteCommand类
type TurnOnCommand struct {
	light *Light
}

func (c *TurnOnCommand) Execute() {
	c.light.TurnOn()
}

type TurnOffCommand struct {
	light *Light
}

func (c *TurnOffCommand) Execute() {
	c.light.TurnOff()
}

// Invoker类
type RemoteControl struct {
	command Command
}

func (r *RemoteControl) SetCommand(command Command) {
	r.command = command
}

func (r *RemoteControl) PressButton() {
	r.command.Execute()
}

func main() {
	light := &Light{}
	turnOn := &TurnOnCommand{light}
	turnOff := &TurnOffCommand{light}

	remote := &RemoteControl{}
	
	// Turn on the light
	remote.SetCommand(turnOn)
	remote.PressButton() // "Light is ON"
	
	// Turn off the light
	remote.SetCommand(turnOff)
	remote.PressButton() // "Light is OFF"
}


15. 解释器模式(Interpreter Pattern)

基本概念
解释器模式为语言的语法提供一个解释器,实现对表达式的解释。该模式常用于实现计算器、SQL解析器、正则表达式引擎等。

结构

  • Expression:抽象表达式,定义解释方法。
  • TerminalExpression:终结符表达式,定义基本的解释操作。
  • NonTerminalExpression:非终结符表达式,定义复杂表达式的解释。

示例(Go语言):

package main

import "fmt"

// Expression接口
type Expression interface {
	Interpret(context string) bool
}

// TerminalExpression类
type TerminalExpression struct {
	data string
}

func (t *TerminalExpression) Interpret(context string) bool {
	return context == t.data
}

// OrExpression类
type OrExpression struct {
	expr1 Expression
	expr2 Expression
}

func (o *OrExpression) Interpret(context string) bool {
	return o.expr1.Interpret(context) || o.expr2.Interpret(context)
}

func main() {
	// Create terminal expressions
	isAdult := &TerminalExpression{data: "Adult"}
	isMale := &TerminalExpression{data: "Male"}

	// Create an OR expression (Adult OR Male)
	orExpression := &OrExpression{expr1: isAdult, expr2: isMale}

	// Interpret the expression
	fmt.Println(orExpression.Interpret("Male"))  // true
	fmt.Println(orExpression.Interpret("Female")) // false
}


16. 迭代器模式(Iterator Pattern)

基本概念
迭代器模式为集合对象提供一个顺序访问其元素的方式,而不暴露集合的内部结构。它使得我们能够遍历集合,且不关心集合的内部实现。

结构

  • Iterator:迭代器接口,提供访问集合元素的方法。
  • ConcreteIterator:具体迭代器,实现迭代器接口。
  • Aggregate:聚合接口,提供创建迭代器的方法。
  • ConcreteAggregate:具体聚合,提供元素集合并创建相应的迭代器。

示例(Go语言):

package main

import "fmt"

// Iterator接口
type Iterator interface {
	HasNext() bool
	Next() string
}

// Aggregate接口
type Aggregate interface {
	CreateIterator() Iterator
}

// ConcreteAggregate类
type ConcreteAggregate struct {
	elements []string
}

func (a *ConcreteAggregate) CreateIterator() Iterator {
	return &ConcreteIterator{aggregate: a, index: 0}
}

// ConcreteIterator类
type ConcreteIterator struct {
	aggregate *ConcreteAggregate
	index     int
}

func (i *ConcreteIterator) HasNext() bool {
	return i.index < len(i.aggregate.elements)
}

func (i *ConcreteIterator) Next() string {
	element := i.aggregate.elements[i.index]
	i.index++
	return element
}

func main() {
	aggregate := &ConcreteAggregate{
		elements: []string{"item1", "item2", "item3"},
	}
	iterator := aggregate.CreateIterator()

	for iterator.HasNext() {
		fmt.Println(iterator.Next())
	}
	// Output:
	// item1
	// item2
	// item3
}


17. 中介者模式(Mediator Pattern)

基本概念
中介者模式定义一个对象,通过它来封装一系列的对象交互,使得对象之间的通信不直接发生,从而减少它们之间的依赖关系。

结构

  • Mediator:中介者接口,声明所有对象通过中介者来进行交互。
  • ConcreteMediator:具体中介者,协调所有对象的交互。
  • Colleague:同事接口,所有同事对象都依赖于中介者。
  • ConcreteColleague:具体同事对象,包含与其他对象交互的逻辑。

示例(Go语言):

package main

import "fmt"

// Mediator接口
type Mediator interface {
	Send(message string, colleague Colleague)
}

// Colleague接口
type Colleague interface {
	Receive(message string)
	Speak(mediator Mediator, message string)
}

// ConcreteColleagueA类
type ConcreteColleagueA struct {
	mediator Mediator
}

func (a *ConcreteColleagueA) Receive(message string) {
	fmt.Println("Colleague A received: " + message)
}

func (a *ConcreteColleagueA) Speak(mediator Mediator, message string) {
	fmt.Println("Colleague A says: " + message)
	mediator.Send(message, a)
}

// ConcreteColleagueB类
type ConcreteColleagueB struct {
	mediator Mediator
}

func (b *ConcreteColleagueB) Receive(message string) {
	fmt.Println("Colleague B received: " + message)
}

func (b *ConcreteColleagueB) Speak(mediator Mediator, message string) {
	fmt.Println("Colleague B says: " + message)
	mediator.Send(message, b)
}

// ConcreteMediator类
type ConcreteMediator struct {
	colleagueA *ConcreteColleagueA
	colleagueB *ConcreteColleagueB
}

func (m *ConcreteMediator) Send(message string, colleague Colleague) {
	if colleague == m.colleagueA {
		m.colleagueB.Receive(message)
	} else if colleague == m.colleagueB {
		m.colleagueA.Receive(message)
	}
}

func main() {
	mediator := &ConcreteMediator{}
	colleagueA := &ConcreteColleagueA{mediator: mediator}
	colleagueB := &ConcreteColleagueB{mediator: mediator}
	mediator.colleagueA = colleagueA
	mediator.colleagueB = colleagueB

	colleagueA.Speak(mediator, "Hello B!")
	colleagueB.Speak(mediator, "Hello A!")
}


18. 备忘录模式(Memento Pattern)

基本概念
备忘录模式保存对象的内部状态,以便在需要时恢复到之前的状态。它不暴露对象的实现细节,确保状态的保存和恢复不影响对象的结构。

结构

  • Memento:备忘录类,保存对象的状态。
  • Originator:发起人类,创建并恢复备忘录。
  • Caretaker:管理者类,负责存储备忘录。

示例(Go语言):

package main

import "fmt"

// Memento类
type Memento struct {
	State string
}

// Originator类
type Originator struct {
	State string
}

func (o *Originator) CreateMemento() *Memento {
	return &Memento{State: o.State}
}

func (o *Originator) SetMemento(memento *Memento) {
	o.State = memento.State
}

// Caretaker类
type Caretaker struct {
	memento *Memento
}

func main() {
	originator := &Originator{State: "State1"}
	caretaker := &Caretaker{}

	// Save current state
	caretaker.memento = originator.CreateMemento()

	// Change state
	originator.State = "State2"
	fmt.Println("Current state:", originator.State) // "State2"

	// Restore previous state
	originator.SetMemento(caretaker.memento)
	fmt.Println("Restored state:", originator.State) // "State1"
}


19. 状态模式(State Pattern)

基本概念
状态模式允许对象在内部状态改变时改变其行为。对象的行为取决于其状态,使得对象看起来好像修改了它的类。

结构

  • State:状态接口,定义与具体状态相关的行为。
  • ConcreteState:具体状态类,负责具体的状态行为。
  • Context:上下文类,持有当前状态,并能在不同的状态之间切换。

示例(Go语言):

package main

import "fmt"

// State接口
type State interface {
	Handle() string
}

// ConcreteStateA类
type ConcreteStateA struct{}

func (s *ConcreteStateA) Handle() string {
	return "Handling in State A"
}

// ConcreteStateB类
type ConcreteStateB struct{}

func (s *ConcreteStateB) Handle() string {
	return "Handling in State B"
}

// Context类
type Context struct {
	state State
}

func (c *Context) SetState(state State) {
	c.state = state
}

func (c *Context) Request() string {
	return c.state.Handle()
}

func main() {
	context := &Context{}

	// Start with State A
	context.SetState(&ConcreteStateA{})
	fmt.Println(context.Request()) // "Handling in State A"

	// Switch to State B
	context.SetState(&ConcreteStateB{})
	fmt.Println(context.Request()) // "Handling in State B"
}


20. 策略模式(Strategy Pattern)

基本概念
策略模式定义了一系列算法,并使得它们可以互换。策略模式让算法独立于使用它的客户而变化,客户端可以选择不同的策略来处理不同的任务。

结构

  • Strategy:策略接口,定义所有支持的算法。
  • ConcreteStrategy:具体策略类,实现不同的算法。
  • Context:上下文类,持有一个策略对象并执行策略。

示例(Go语言):

package main

import "fmt"

// Strategy接口
type Strategy interface {
	Execute(a, b int) int
}

// ConcreteStrategyA类
type ConcreteStrategyA struct{}

func (s *ConcreteStrategyA) Execute(a, b int) int {
	return a + b
}

// ConcreteStrategyB类
type ConcreteStrategyB struct{}

func (s *ConcreteStrategyB) Execute(a, b int) int {
	return a * b
}

// Context类
type Context struct {
	strategy Strategy
}

func (c *Context) SetStrategy(strategy Strategy) {
	c.strategy = strategy
}

func (c *Context) ExecuteStrategy(a, b int) int {
	return c.strategy.Execute(a, b)
}

func main() {
	context := &Context{}

	// Use strategy A (addition)
	context.SetStrategy(&ConcreteStrategyA{})
	fmt.Println("Addition: ", context.ExecuteStrategy(3, 4)) // "Addition: 7"

	// Use strategy B (multiplication)
	context.SetStrategy(&ConcreteStrategyB{})
	fmt.Println("Multiplication: ", context.ExecuteStrategy(3, 4)) // "Multiplication: 12"
}


21. 模板方法模式(Template Method Pattern)

基本概念
模板方法模式定义一个算法的骨架,将一些步骤的实现延迟到子类中。子类可以在不改变算法结构的情况下,重新定义算法的某些步骤。

结构

  • AbstractClass:抽象类,定义算法的模板。
  • ConcreteClass:具体类,实现算法的具体步骤。

示例(Go语言):

package main

import "fmt"

// AbstractClass类
type AbstractClass struct{}

func (a *AbstractClass) TemplateMethod() {
	a.Step1()
	a.Step2()
}

func (a *AbstractClass) Step1() {
	fmt.Println("Step 1: Common implementation")
}

func (a *AbstractClass) Step2() {
	fmt.Println("Step 2: Abstract, to be implemented by subclass")
}

// ConcreteClass类
type ConcreteClass struct {
	AbstractClass
}

func (c *ConcreteClass) Step2() {
	fmt.Println("Step 2: Concrete implementation")
}

func main() {
	class := &ConcreteClass{}
	class.TemplateMethod()
	// Output:
	// Step 1: Common implementation
	// Step 2: Concrete implementation
}


22. 访问者模式(Visitor Pattern)

基本概念
访问者模式将数据结构与作用于数据的操作分离。通过引入一个新的访问者对象来执行操作,避免修改数据结构本身。

结构

  • Visitor:访问者接口,声明访问操作。
  • ConcreteVisitor:具体访问者,实现对不同元素的访问操作。
  • Element:元素接口,定义接受访问者的接口。
  • ConcreteElement:具体元素,接收访问者的操作。
  • ObjectStructure:包含元素的集合。

示例(Go语言):

package main

import "fmt"

// Visitor接口
type Visitor interface {
	Visit(Element)
}

// Element接口
type Element interface {
	Accept(Visitor)
}

// ConcreteElement类
type ConcreteElement struct {
	name string
}

func (e *ConcreteElement) Accept(visitor Visitor) {
	visitor.Visit(e)
}

// ConcreteVisitor类
type ConcreteVisitor struct{}

func (v *ConcreteVisitor) Visit(element Element) {
	if e, ok := element.(*ConcreteElement); ok {
		fmt.Println("Visiting element:", e.name)
	}
}

func main() {
	element := &ConcreteElement{name: "Element1"}
	visitor := &ConcreteVisitor{}

	element.Accept(visitor) // "Visiting element: Element1"
}


23. 备忘录模式(Memento Pattern)

基本概念
备忘录模式用于保存和恢复对象的状态,它不暴露对象的内部结构,并且可以在对象状态改变时进行备份。

结构

  • Memento:备忘录类,保存对象的状态。
  • Originator:发起人类,创建并恢复备忘录。
  • Caretaker:管理者类,负责存储备忘录。

示例(Go语言):

package main

import "fmt"

// Memento类
type Memento struct {
	State string
}

// Originator类
type Originator struct {
	State string
}

func (o *Originator) CreateMemento() *Memento {
	return &Memento{State: o.State}
}

func (o *Originator) SetMemento(memento *Memento) {
	o.State = memento.State
}

// Caretaker类
type Caretaker struct {
	memento *Memento
}

func main() {
	originator := &Originator{State: "State1"}
	caretaker := &Caretaker{}

	// Save current state
	caretaker.memento = originator.CreateMemento()

	// Change state
	originator.State = "State2"
	fmt.Println("Current state:", originator.State) // "State2"

	// Restore previous state
	originator.SetMemento(caretaker.memento)
	fmt.Println("Restored state:", originator.State) // "State1"
}


总结

以上就是 23种设计模式 的基本概念、结构和示例代码。每种设计模式都解决了不同类型的设计问题,并且在开发中有着非常广泛的应用。

  • 创建型模式:主要关注如何实例化对象。
  • 结构型模式:主要关注如何组合对象,形成更大的结构。
  • 行为型模式:主要关注对象间的交互和责任分配。

这些模式的实际应用能够显著提高代码的可维护性、可扩展性和灵活性。

文章标签:

评论(0)