golang 设计模式-Creational

本文介绍了Go(Golang)语言中的五种创建型设计模式:Singleton、Builder、Factory Method、Abstract Factory和Prototype。Singleton确保了程序中只有一个实例;Builder模式用于构建复杂对象,允许分离对象的构建过程和表示;Factory Method将对象的创建委托给子类;Abstract Factory则提供了一组工厂来创建相关对象家族;Prototype模式允许在运行时复制已有对象,减少创建新对象的开销。每个模式都配有示例和测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建型模式:Singleton、Builder、Factory Method、Abstract Factory、Prototype

Singleton 单例设计模式

having a unique instance of a type in the entire program
在整个程序中只具有某一类型的唯一实例

示例:唯一的计数器

package creational
type singleton struct {
   
	count int
}

var instance *singleton

func GetInstance() *singleton {
   
	if instance == nil {
   
		instance = new(singleton)
	}
	return new(singleton)
}
func (s *singleton) AddOne() int {
   
	s.count++
	return s.count
}

测例 go test -v ./patterns/creational -cover

package creational
import (
	"testing"
)

func Test_singleton_AddOne(t *testing.T) {
   
	c1 := GetInstance()
	currentCount := c1.AddOne()
	if currentCount != 1 {
   
		t.Errorf("After calling for the first time to count, the count must be1 but it is %d\n", currentCount)
	}
	c2 := GetInstance()
	currentCount = c2.AddOne()
	if currentCount != 2 {
   
		t.Errorf("After calling 'AddOne' using the second counter, the currentcount must be 2 but was %d\n", currentCount)
	}
}

func TestGetInstance(t *testing.T) {
   
	c1 := GetInstance()
	c2 := GetInstance()
	if c1 == nil || c2 == nil {
   
		t.Errorf("expected pointer to Singleton after calling GetInstance(), not nil")
	}
	if c1 != c2 {
   
		t.Errorf("Expected same instance in counter2 but it got a different instance")
	}

}

Builder 建造者设计模式

reusing an algorithm to create many implementations of an interface
重用某个算法来创建接口的多个实现

例如,你将使用几乎相同的技术来建造一辆汽车,你将建造一辆公共汽车,除了他们将不同的大小和座位的数量,所以我们为什么不重复建造过程(组装结构,放置车轮,放置座椅)?
示例:车辆制造
核心思想:ManufacturingDirector负责重用建造过程

package creational

//产品接口,开放更改
type VehicleProduct struct {
   
	Wheels    int
	Seats     int
	Structure string
}

//定义一组车辆建造的行为
type BuildProcess interface {
   
	SetWheels() BuildProcess
	SetSeats() BuildProcess
	SetStructure() BuildProcess
	Build() VehicleProduct
}

//----------导演
type ManufacturingDirector struct {
   
	bp BuildProcess
}

//使用BuildProcess进行产品构造
func (f *ManufacturingDirector) Construct() {
   
	//Implementation goes here
	f.bp.SetSeats().SetWheels().SetStructure()
}
func (f *ManufacturingDirector) SetBuilder(b BuildProcess) {
   
	//Implementation goes here
	f.bp = b
}

//----------小车建造器
type CarBuilder struct {
   
	v VehicleProduct
}

func (c *CarBuilder) SetWheels() BuildProcess {
   
	c.v.Wheels = 4
	return c
}
func (c *CarBuilder) SetSeats() BuildProcess {
   
	c.v.Seats = 5
	return c
}
func (c *CarBuilder) SetStructure() BuildProcess {
   
	c.v.Structure = "Car"
	return c
}
func (c *CarBuilder) Build() VehicleProduct {
    return c.v }

//--------摩托车建造器
type BikeBuilder struct {
   
	v VehicleProduct
}

func (b *BikeBuilder) SetWheels() BuildProcess {
   
	b.v.Wheels = 2
	return b
}
func (b *BikeBuilder) SetSeats() BuildProcess {
   
	b.v.Seats = 2
	return b
}
func (b *BikeBuilder) SetStructure() BuildProcess {
   
	b.v.Structure = "Motorbike"
	return b
}
func (b *BikeBuilder) Build() VehicleProduct {
    return b.v }

测例

package creational

import &#
### 如何使用 Keil5 烧录 Hex 文件 对于仅拥有已编译好的 hex 文件而无源文件的情况,在 Keil V5 平台上直接烧录 hex 文件至单片机(如华大单片机)需采取特定的方法,因为直接调用该平台进行此类操作不可行[^1]。 #### 设置 Output 路径 进入 Keil 的 output 设置界面,指定要烧录的 hex 文件的具体位置。确保在路径输入框中填写完整的 hex 文件名称并附带 `.hex` 扩展名;缺少此扩展名可能导致系统继续尝试烧录先前编译的结果而非所选的 hex 文件[^3]。 #### 配置 Flash 工具选项 针对不同类型的微控制器(MCU),可能还需调整 flash 下载工具的相关配置参数以匹配目标设备的要求。这一步骤通常涉及选择合适的编程算法以及设定通信接口等细节[^2]。 #### 启动下载过程 完成上述准备工作之后,可以通过点击调试窗口内的 “Download” 或者快捷菜单里的相应命令来启动实际的程序写入流程。如果一切顺利的话,软件会自动连接硬件并将选定的 hex 数据传输到 MCU 中存储起来[^4]。 ```python # Python 示例代码用于说明自动化脚本概念 (并非真实实现) def download_hex_to_mcu(hex_file_path, mcu_type): """ 自定义函数模拟将 HEX 文件下载到指定型号的 MCU 上 参数: hex_file_path -- 完整路径字符串指向待上传的 .hex 文件 mcu_type -- 字符串表示的目标单片机类型标识符 返回值: 成功则返回 True ,失败抛出异常信息 """ try: configure_output_settings(hex_file_path) # 设定输出设置 select_flash_tool(mcu_type) # 挑选适合的闪存工具 execute_download_command() # 发送下载指令 return True # 表明成功结束 except Exception as e: raise RuntimeError(f"Failed to upload {hex_file_path}: {e}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值