兄弟们,chatgpt 生成的设计模式,生成到 17个的时候没了。大家看看代码质量如何

在软件开发中,设计模式是一种被广泛应用的编程思想。设计模式是一种可重用的解决方案,它可以帮助我们解决一些常见的编程问题,提高代码的可读性、可维护性和可扩展性。本文将为大家介绍23种设计模式,并提供golang代码示例,希望能够帮助大家更好地理解和应用设计模式。

  1. 工厂方法模式(Factory Method Pattern)
    工厂方法模式是一种创建型模式,它提供了一种将对象的创建委托给子类的方法。在工厂方法模式中,我们定义一个创建对象的接口,但让子类决定实例化哪个类。例如:
type Product interface {
    getName() string
}

type ConcreteProduct struct {
    name string
}

func (p *ConcreteProduct) getName() string {
    return p.name
}

type Factory interface {
    createProduct() Product
}

type ConcreteFactory struct {}

func (f *ConcreteFactory) createProduct() Product {
    return &ConcreteProduct{name: "concrete product"}
}
  1. 抽象工厂模式(Abstract Factory Pattern)
    抽象工厂模式是一种创建型模式,它提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。例如:
type Shape interface {
    draw()
}

type Rectangle struct {}

func (r *Rectangle) draw() {
    fmt.Println("rectangle")
}

type Circle struct {}

func (c *Circle) draw() {
    fmt.Println("circle")
}

type Factory interface {
    createShape() Shape
}

type RectangleFactory struct {}

func (f *RectangleFactory) createShape() Shape {
    return &Rectangle{}
}

type CircleFactory struct {}

func (f *CircleFactory) createShape() Shape {
    return &Circle{}
}
  1. 单例模式(Singleton Pattern)
    单例模式是一种创建型模式,它保证一个类只有一个实例,并提供一个全局访问点。例如:
type Singleton struct{}

var instance *Singleton

func GetInstance() *Singleton {
    if instance == nil {
        instance = &Singleton{}
    }
    return instance
}
  1. 建造者模式(Builder Pattern)
    建造者模式是一种创建型模式,它将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。例如:
type Builder interface {
    buildPartA()
    buildPartB()
    getResult() *Product
}

type Product struct {
    partA string
    partB string
}

type ConcreteBuilder struct {
    product *Product
}

func (b *ConcreteBuilder) buildPartA() {
    b.product.partA = "part A"
}

func (b *ConcreteBuilder) buildPartB() {
    b.product.partB = "part B"
}

func (b *ConcreteBuilder) getResult() *Product {
    return b.product
}

type Director struct {
    builder Builder
}

func (d *Director) construct() *Product {
    d.builder.buildPartA()
    d.builder.buildPartB()
    return d.builder.getResult()
}
  1. 原型模式(Prototype Pattern)
    原型模式是一种创建型模式,它允许通过复制现有对象来创建新对象,而不是通过实例化来创建。例如:
type Prototype interface {
    clone() Prototype
}

type ConcretePrototype struct {
    name string
}

func (p *ConcretePrototype) clone() Prototype {
    return &ConcretePrototype{name: p.name}
}
  1. 适配器模式(Adapter Pattern)
    适配器模式是一种结构型模式,它将一个类的接口转换成客户希望的另一个接口。例如:
type Target interface {
    request()
}

type Adaptee struct{}

func (a *Adaptee) specificRequest() {
    fmt.Println("specific request")
}

type Adapter struct {
    adaptee *Adaptee
}

func (a *Adapter) request() {
    a.adaptee.specificRequest()
}
  1. 桥接模式(Bridge Pattern)
    桥接模式是一种结构型模式,它将抽象部分与它的实现部分分离,使它们可以独立地变化。例如:
type Implementor interface {
    operationImpl()
}

type ConcreteImplementorA struct{}

func (i *ConcreteImplementorA) operationImpl() {
    fmt.Println("operation A")
}

type ConcreteImplementorB struct{}

func (i *ConcreteImplementorB) operationImpl() {
    fmt.Println("operation B")
}

type Abstraction interface {
    operation()
}

type RefinedAbstraction struct {
    implementor Implementor
}

func (a *RefinedAbstraction) operation() {
    a.implementor.operationImpl()
}
  1. 组合模式(Composite Pattern)
    组合模式是一种结构型模式,它将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。例如:
type Component interface {
    operation()
}

type Leaf struct{}

func (l *Leaf) operation() {
    fmt.Println("leaf")
}

type Composite struct {
    components []Component
}

func (c *Composite) add(component Component) {
    c.components = append(c.components, component)
}

func (c *Composite) operation() {
    for _, component := range c.components {
        component.operation()
    }
}
  1. 装饰器模式(Decorator Pattern)
    装饰器模式是一种结构型模式,它动态地给一个对象添加一些额外的职责,同时又不改变其结构。例如:
type Component interface {
    operation()
}

type ConcreteComponent struct{}

func (c *ConcreteComponent) operation() {
    fmt.Println("concrete component")
}

type Decorator interface {
    operation()
}

type ConcreteDecoratorA struct {
    component Component
}

func (d *ConcreteDecoratorA) operation() {
    d.component.operation()
    fmt.Println("concrete decorator A")
}

type ConcreteDecoratorB struct {
    component Component
}

func (d *ConcreteDecoratorB) operation() {
    d.component.operation()
    fmt.Println("concrete decorator B")
}
  1. 外观模式(Facade Pattern)
    外观模式是一种结构型模式,它为子系统中的一组接口提供一个统一的接口,使得子系统更容易使用。例如:
type SubsystemA struct{}

func (s *SubsystemA) operationA() {
    fmt.Println("subsystem A")
}

type SubsystemB struct{}

func (s *SubsystemB) operationB() {
    fmt.Println("subsystem B")
}

type Facade struct {
    subsystemA *SubsystemA
    subsystemB *SubsystemB
}

func (f *Facade) operation() {
    f.subsystemA.operationA()
    f.subsystemB.operationB()
}
  1. 享元模式(Flyweight Pattern)
    享元模式是一种结构型模式,它通过共享技术来减少对象的数量,从而减少内存占用和提高性能。例如:
type Flyweight interface {
    operation(state string)
}

type ConcreteFlyweight struct{}

func (f *ConcreteFlyweight) operation(state string) {
    fmt.Println("concrete flyweight: ", state)
}

type FlyweightFactory struct {
    flyweights map[string]Flyweight
}

func (f *FlyweightFactory) getFlyweight(key string) Flyweight {
    if flyweight, ok := f.flyweights[key]; ok {
        return flyweight
    } else {
        flyweight = &ConcreteFlyweight{}
        f.flyweights[key] = flyweight
        return flyweight
    }
}
  1. 代理模式(Proxy Pattern)
    代理模式是一种结构型模式,它为其他对象提供一种代理以控制对这个对象的访问。例如:
type Subject interface {
    request()
}

type RealSubject struct{}

func (s *RealSubject) request() {
    fmt.Println("real subject")
}

type Proxy struct {
    realSubject *RealSubject
}

func (p *Proxy) request() {
    if p.realSubject == nil {
        p.realSubject = &RealSubject{}
    }
    p.realSubject.request()
}
  1. 责任链模式(Chain of Responsibility Pattern)
    责任链模式是一种行为型模式,它通过一条链来组织请求的处理,每个节点可以选择处理请求或将其传递给下一个节点。例如:
type Handler interface {
    handleRequest(request string)
    setNext(handler Handler)
}

type ConcreteHandlerA struct {
    next Handler
}

func (h *ConcreteHandlerA) handleRequest(request string) {
    if request == "A" {
        fmt.Println("concrete handler A")
    } else if h.next != nil {
        h.next.handleRequest(request)
    }
}

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

type ConcreteHandlerB struct {
    next Handler
}

func (h *ConcreteHandlerB) handleRequest(request string) {
    if request == "B" {
        fmt.Println("concrete handler B")
    } else if h.next != nil {
        h.next.handleRequest(request)
    }
}

func (h *ConcreteHandlerB) setNext(handler Handler) {
    h.next = handler
}
  1. 命令模式(Command Pattern)
    命令模式是一种行为型模式,它将请求封装成对象,从而使得可以用不同的请求来参数化其他对象。例如:
type Command interface {
    execute()
}

type Receiver struct{}

func (r *Receiver) action() {
    fmt.Println("receiver action")
}

type ConcreteCommand struct {
    receiver *Receiver
}

func (c *ConcreteCommand) execute() {
    c.receiver.action()
}

type Invoker struct {
    command Command
}

func (i *Invoker) setCommand(command Command) {
    i.command = command
}

func (i *Invoker) executeCommand() {
    i.command.execute()
}
  1. 迭代器模式(Iterator Pattern)
    迭代器模式是一种行为型模式,它提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。例如:
type Iterator interface {
    hasNext() bool
    next() interface{}
}

type Aggregate interface {
    createIterator() Iterator
}

type ConcreteIterator struct {
    data []interface{}
    index int
}

func (i *ConcreteIterator) hasNext() bool {
    return i.index < len(i.data)
}

func (i *ConcreteIterator) next() interface{} {
    if i.hasNext() {
        value := i.data[i.index]
        i.index++
        return value
    } else {
        return nil
    }
}

type ConcreteAggregate struct {
    data []interface{}
}

func (a *ConcreteAggregate) createIterator() Iterator {
    return &ConcreteIterator{data: a.data, index: 0}
}
  1. 中介者模式(Mediator Pattern)
    中介者模式是一种行为型模式,它通过一个中介对象来封装一系列对象之间的交互,从而使得这些对象之间的交互变得松散耦合。例如:
type Mediator interface {
    send(message string, colleague Colleague)
}

type Colleague interface {
    receive(message string)
}

type ConcreteMediator struct {
    colleagues []Colleague
}

func (m *ConcreteMediator) send(message string, colleague Colleague) {
    for _, c := range m.colleagues {
        if c != colleague {
            c.receive(message)
        }
    }
}

type ConcreteColleagueA struct {
    mediator Mediator
}

func (c *ConcreteColleagueA) receive(message string) {
    fmt.Println("concrete colleague A received: ", message)
}

func (c *ConcreteColleagueA) send(message string) {
    c.mediator.send(message, c)
}

type ConcreteColleagueB struct {
    mediator Mediator
}

func (c *ConcreteColleagueB) receive(message string) {
    fmt.Println("concrete colleague B received: ", message)
}

func (c *ConcreteColleagueB) send(message string) {
    c.mediator.send(message, c)
}
  1. 备忘录模式(Memento Pattern)
    备忘录模式是一种行为型模式,它在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。例如:

```
type Memento

本作品采用《CC 协议》,转载必须注明作者和本文链接
九九一十八,一步一个脚印
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!