当前位置: 首页 > news >正文

使用Golang实现开发中常用的【实例设计模式】

使用Golang实现开发中常用的【实例设计模式】

设计模式是解决常见问题的模板,可以帮助我们提升思维能力,编写更高效、可维护性更强的代码。

单例模式:

描述:确保一个类只有一个实例,并提供一个全局访问点。
优点:节省资源,避免重复创建对象。
缺点:单例对象通常是全局可访问的,容易引起耦合。

package singletonimport ("sync"
)type Singleton struct {value string
}var instance *Singleton
var once sync.Oncefunc GetInstance() *Singleton {once.Do(func() {instance = &Singleton{}})return instance
}func (s *Singleton) SetValue(value string) {s.value = value
}func (s *Singleton) GetValue() string {return s.value
}

工厂模式:

描述:提供一个创建对象的接口,但由子类决定实例化哪一个类。
优点:将对象的创建和使用分离,提高代码的灵活性。
缺点:增加了代码的复杂性。

package factorytype Product interface {Use()
}type ConcreteProductA struct{}func (p *ConcreteProductA) Use() {println("Using ConcreteProductA")
}type ConcreteProductB struct{}func (p *ConcreteProductB) Use() {println("Using ConcreteProductB")
}type Factory interface {CreateProduct() Product
}type ConcreteFactoryA struct{}func (f *ConcreteFactoryA) CreateProduct() Product {return &ConcreteProductA{}
}type ConcreteFactoryB struct{}func (f *ConcreteFactoryB) CreateProduct() Product {return &ConcreteProductB{}
}

观察者模式:

描述:定义了对象之间的一对多依赖关系,当一个对象的状态改变时,所有依赖于它的对象都会得到通知。
优点:实现了对象之间的松耦合。
缺点:如果观察者数量过多,通知过程可能会变得复杂。

package observertype Subject interface {RegisterObserver(observer Observer)RemoveObserver(observer Observer)NotifyObservers()
}type Observer interface {Update(data string)
}type ConcreteSubject struct {observers []Observerstate     string
}func (s *ConcreteSubject) RegisterObserver(observer Observer) {s.observers = append(s.observers, observer)
}func (s *ConcreteSubject) RemoveObserver(observer Observer) {for i, obs := range s.observers {if obs == observer {s.observers = append(s.observers[:i], s.observers[i+1:]...)break}}
}func (s *ConcreteSubject) NotifyObservers() {for _, observer := range s.observers {observer.Update(s.state)}
}func (s *ConcreteSubject) SetState(state string) {s.state = states.NotifyObservers()
}type ConcreteObserver struct {name string
}func (o *ConcreteObserver) Update(data string) {println(o.name, "received:", data)
}

策略模式:

描述:定义一系列算法,把它们一个个封装起来,并且使它们可以互相替换。
优点:算法的变化独立于使用算法的客户。
缺点:增加了代码的复杂性。

package strategytype Strategy interface {Execute(data string) string
}type Context struct {strategy Strategy
}func (c *Context) SetStrategy(strategy Strategy) {c.strategy = strategy
}func (c *Context) ExecuteStrategy(data string) string {return c.strategy.Execute(data)
}type ConcreteStrategyA struct{}func (s *ConcreteStrategyA) Execute(data string) string {return "ConcreteStrategyA executed with " + data
}type ConcreteStrategyB struct{}func (s *ConcreteStrategyB) Execute(data string) string {return "ConcreteStrategyB executed with " + data
}

装饰者模式:

描述:动态地给一个对象添加一些额外的职责,而不必修改对象结构。
优点:增加了代码的灵活性和可扩展性。
缺点:增加了代码的复杂性。

package decoratortype Component interface {Operation() string
}type ConcreteComponent struct{}func (c *ConcreteComponent) Operation() string {return "ConcreteComponent operation"
}type Decorator struct {component Component
}func NewDecorator(component Component) *Decorator {return &Decorator{component: component}
}func (d *Decorator) Operation() string {return d.component.Operation()
}type ConcreteDecoratorA struct {Decorator
}func (d *ConcreteDecoratorA) Operation() string {return "ConcreteDecoratorA added to " + d.Decorator.Operation()
}type ConcreteDecoratorB struct {Decorator
}func (d *ConcreteDecoratorB) Operation() string {return "ConcreteDecoratorB added to " + d.Decorator.Operation()
}

代理模式:

描述:为其他对象提供一种代理以控制对这个对象的访问。
优点:增加了安全性和灵活性。
缺点:增加了代码的复杂性。

package proxytype Subject interface {Request() string
}type RealSubject struct{}func (r *RealSubject) Request() string {return "RealSubject handling request"
}type Proxy struct {realSubject *RealSubject
}func NewProxy() *Proxy {return &Proxy{realSubject: &RealSubject{},}
}func (p *Proxy) Request() string {// Pre-processingprintln("Proxy: Checking access prior to firing a real request.")// Delegate to the real subjectresult := p.realSubject.Request()// Post-processingprintln("Proxy: Logging the time of request.")return result
}

分别调用不同模式的对象实例:

package mainimport ("fmt""singleton""factory""observer""strategy""decorator""proxy"
)func main() {// 单例模式singleton.GetInstance().SetValue("Hello, Singleton!")fmt.Println(singleton.GetInstance().GetValue())// 工厂模式factoryA := &factory.ConcreteFactoryA{}productA := factoryA.CreateProduct()productA.Use()factoryB := &factory.ConcreteFactoryB{}productB := factoryB.CreateProduct()productB.Use()// 观察者模式subject := &observer.ConcreteSubject{}observerA := &observer.ConcreteObserver{name: "ObserverA"}observerB := &observer.ConcreteObserver{name: "ObserverB"}subject.RegisterObserver(observerA)subject.RegisterObserver(observerB)subject.SetState("New State")// 策略模式context := &strategy.Context{}strategyA := &strategy.ConcreteStrategyA{}strategyB := &strategy.ConcreteStrategyB{}context.SetStrategy(strategyA)fmt.Println(context.ExecuteStrategy("Data"))context.SetStrategy(strategyB)fmt.Println(context.ExecuteStrategy("Data"))// 装饰者模式component := &decorator.ConcreteComponent{}decoratorA := &decorator.ConcreteDecoratorA{Decorator: *decorator.NewDecorator(component)}decoratorB := &decorator.ConcreteDecoratorB{Decorator: *decorator.NewDecorator(decoratorA)}fmt.Println(decoratorB.Operation())// 代理模式proxy := proxy.NewProxy()fmt.Println(proxy.Request())
}

相关文章:

使用Golang实现开发中常用的【实例设计模式】

使用Golang实现开发中常用的【实例设计模式】 设计模式是解决常见问题的模板,可以帮助我们提升思维能力,编写更高效、可维护性更强的代码。 单例模式: 描述:确保一个类只有一个实例,并提供一个全局访问点。 优点&…...

【Java学习】电脑基础操作和编程环境配置

CMD 在Windows中用命令行的方式操作计算机。 打开CMD Win R输入CMD按下回车键 Win E 进入我的电脑 常用的CMD命令 盘符名称冒号 说明:盘符切换 举例:E:回车,表示切换到E盘 dir 说明:查看当前路径下的内容 cd目录 说明&a…...

AVL树解析

目录 一. AVL的概念 二 AVL树的插入 2.1先按二叉搜索树的规则插入 2.2 AVL的重点:平衡因子更新 3.1 更新后parent的平衡因子等于0。 3.2 更新后parent的平衡因子等于1 或 -1,需要继续往上更新。 3.3 更新后parent的平衡因子等于2 或 -2,需…...

栈和队列(Java)

一.栈(Stack) 1.定义 栈是限定仅在表尾进行插入或删除操作的线性表 一般的表尾称为栈顶 表头称为栈底 栈具有“后进先出”的特点 2.对栈的模拟 栈主要具有以下功能: push(Object item):将元素item压入栈顶。 pop()&am…...

C#设计原则

文章目录 项目地址一、开放封闭原则1.1 不好的版本1.2 将BankProcess的实现改为接口1.3 修改BankStuff类和IBankClient类二、依赖倒置原则2.1 高层不应该依赖于低层模块2.1.1 不好的例子2.1.2 修改:将各个国家的歌曲抽象2.2 抽象不应该依于细节2.2.1 不同的人开不同的车(接口…...

easyfs 简易文件系统

easyfs easyfs 简易文件系统文件系统虚拟文件系统 VFS简易文件系统 easyfs磁盘布局超级块 easyfs 文件系统结构磁盘上的索引结构索引节点Inode 和 DiskInode 之间的关系举例说明读取文件的过程( /hello ) 参考文档 easyfs 简易文件系统 文件系统 常规文…...

【架构论文-1】面向服务架构(SOA)

【摘要】 本文以我参加公司的“生产线数字孪生”项目为例,论述了“面向服务架构设计及其应用”。该项目的目标是构建某车企的数字孪生平台,在虚拟场景中能够仿真还原真实产线的动作和节拍,实现虚实联动,从而提前规避问题&#xff…...

刚刚!更新宁德时代社招Verify测评语言理解数字推理SHL题库、网盘资料、高分答案

宁德时代社招入职的Verify测评主要分为两大块:语言理解和数字推理。语言理解部分包括阅读理解、逻辑填空和语句排序,要求在17分钟内完成30题。数字推理部分包括数字序列、数学问题解决和图表分析,同样要求在17分钟内完成18题。这些测评题目旨…...

C++笔记---智能指针

1. 什么是智能指针 1.1 RALL设计思想 RAII(Resource Acquisition Is Initialization,资源获取即初始化)是一种资源管理类的设计思想,广泛应用于C等支持对象导向编程的语言中。它的核心思想是将资源的管理与对象的生命周期紧密绑定…...

CentOS 7系统中更改YUM源为阿里云的镜像源

引言 更换阿里的镜像源可以带来诸多好处,包括提高下载速度、提升稳定性、同步更新、简化配置、节省带宽资源以及增强系统安全性等。因此,对于使用CentOS系统的用户来说,更换阿里的镜像源是一个值得考虑的选择。 1.备份yum源 mv /etc/yum.r…...

Python酷库之旅-第三方库Pandas(206)

目录 一、用法精讲 961、pandas.IntervalIndex.mid属性 961-1、语法 961-2、参数 961-3、功能 961-4、返回值 961-5、说明 961-6、用法 961-6-1、数据准备 961-6-2、代码示例 961-6-3、结果输出 962、pandas.IntervalIndex.length属性 962-1、语法 962-2、参数 …...

3.4CQU数学实验???

meshgrid 是一个用于生成网格点坐标的函数。它常用于在二维或三维空间中创建坐标网格,用于可视化和数据处理。 在二维情况下,meshgrid 函数接受两个一维数组作为输入,并返回两个二维数组,这两个数组中的元素分别表示了所有可能的…...

Linux(CentOS)开放端口/关闭端口

一、普通用户使用 sudo 操作,开放/关闭端口,80 1、检查端口是否开放 sudo firewall-cmd --zonepublic --query-port80/tcp 2、开放端口 sudo firewall-cmd --zonepublic --add-port80/tcp --permanent 3、重新加载(开放或关闭端口后都需…...

GreenDao适配AGP8.7+

升级配置 工具版本Android StudioLadybug 2024.2.1 Path2AGP8.7.2KPG1.8.21GGP3.3.1明细 classpath "com.android.tools.build:gradle:$agp_version"classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kgp_version"classpath "org.greenrobot:g…...

【前端】Typescript从入门到进阶

以下是 TypeScript 的常用知识点总结,涵盖了从基础到入门的内容,并配有代码示例: 1. TypeScript 基础 1.1 安装和配置 安装 TypeScript 并初始化配置文件: npm install -g typescript tsc --init 1.2 基本类型 TypeScript 提供…...

在 RHEL 8 | CentOS Linux release 8.5.2111上安装 Zabbix 6

1. 备份YUM源文件 cd /etc/yum.repos.d/ mkdir bak mv C* ./bak/ wget -O /etc/yum.repos.d/CentOS-Linux-BaseOS.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo yum clean all yum makecache2. 将 SELinux 设置为宽容模式,如下所示。 sudo s…...

光纤HDMI线怎么连接回音壁?

第一步:准备HDMI线、光纤线(TOSLINK线)、视频源设备、回音壁 第二步:连接HDMI线,找到视频源设备上的HDMI输出口,将HDMI线的一端插入这个接口,再把HDMI线的另一端插入回音壁的HDMI输入口。注意检…...

屏幕后期处理

1、屏幕后期处理效果 屏幕后期处理效果( Screen Post-Processing Effects)是一种在渲染管线的最后阶段应用的视觉效果,允许在场景渲染完成后对最终图像进行各种调整和效果处理,从而增强视觉体验 常见的屏幕后期处理效果有&#x…...

K8资源之endpoint资源EP资源

1 endpoint资源概述 endpoint资源在K8S中用来表s示vc与后端 Pod 之间的连接关系的对象。当创建svc时,svc根据标签是否相同或svc名字是否和ep名字相同,把svc和ip关联上。 删除svc时,会自动的删除同名的ep资源。 2 ep资源和svc的关联测试 […...

微软日志丢失事件敲响安全警钟

NEWS | 事件回顾 最近,全球最大的软件公司之一——微软,遭遇了一场罕见的日志丢失危机。据报告,从9月2日至9月19日,持续长达两周的时间里,微软的多项核心云服务,包括身份验证平台Microsoft Entra、安全信息…...

大数据学习栈记——Neo4j的安装与使用

本文介绍图数据库Neofj的安装与使用,操作系统:Ubuntu24.04,Neofj版本:2025.04.0。 Apt安装 Neofj可以进行官网安装:Neo4j Deployment Center - Graph Database & Analytics 我这里安装是添加软件源的方法 最新版…...

synchronized 学习

学习源: https://www.bilibili.com/video/BV1aJ411V763?spm_id_from333.788.videopod.episodes&vd_source32e1c41a9370911ab06d12fbc36c4ebc 1.应用场景 不超卖,也要考虑性能问题(场景) 2.常见面试问题: sync出…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言: 通过AI视觉技术,为船厂提供全面的安全监控解决方案,涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面,能够实现对应负责人反馈机制,并最终实现数据的统计报表。提升船厂…...

STM32标准库-DMA直接存储器存取

文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA(Direct Memory Access)直接存储器存取 DMA可以提供外设…...

Java-41 深入浅出 Spring - 声明式事务的支持 事务配置 XML模式 XML+注解模式

点一下关注吧!!!非常感谢!!持续更新!!! 🚀 AI篇持续更新中!(长期更新) 目前2025年06月05日更新到: AI炼丹日志-28 - Aud…...

多种风格导航菜单 HTML 实现(附源码)

下面我将为您展示 6 种不同风格的导航菜单实现&#xff0c;每种都包含完整 HTML、CSS 和 JavaScript 代码。 1. 简约水平导航栏 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport&qu…...

AspectJ 在 Android 中的完整使用指南

一、环境配置&#xff08;Gradle 7.0 适配&#xff09; 1. 项目级 build.gradle // 注意&#xff1a;沪江插件已停更&#xff0c;推荐官方兼容方案 buildscript {dependencies {classpath org.aspectj:aspectjtools:1.9.9.1 // AspectJ 工具} } 2. 模块级 build.gradle plu…...

Razor编程中@Html的方法使用大全

文章目录 1. 基础HTML辅助方法1.1 Html.ActionLink()1.2 Html.RouteLink()1.3 Html.Display() / Html.DisplayFor()1.4 Html.Editor() / Html.EditorFor()1.5 Html.Label() / Html.LabelFor()1.6 Html.TextBox() / Html.TextBoxFor() 2. 表单相关辅助方法2.1 Html.BeginForm() …...

Windows安装Miniconda

一、下载 https://www.anaconda.com/download/success 二、安装 三、配置镜像源 Anaconda/Miniconda pip 配置清华镜像源_anaconda配置清华源-CSDN博客 四、常用操作命令 Anaconda/Miniconda 基本操作命令_miniconda创建环境命令-CSDN博客...

解决:Android studio 编译后报错\app\src\main\cpp\CMakeLists.txt‘ to exist

现象&#xff1a; android studio报错&#xff1a; [CXX1409] D:\GitLab\xxxxx\app.cxx\Debug\3f3w4y1i\arm64-v8a\android_gradle_build.json : expected buildFiles file ‘D:\GitLab\xxxxx\app\src\main\cpp\CMakeLists.txt’ to exist 解决&#xff1a; 不要动CMakeLists.…...