添加抽象工厂模式示例,包含手机和笔记本电脑的具体产品及工厂实现,并更新相关文档和构建脚本

This commit is contained in:
2025-12-09 01:33:55 +08:00
parent 7498a885fc
commit c5c0cf76b2
7 changed files with 194 additions and 8 deletions
+28
View File
@@ -0,0 +1,28 @@
BUILDDIR := build
DIRS := $(shell ls -d */)
.PHONY: build
build:
mkdir -p $(BUILDDIR); \
for dir in $(DIRS); do \
if [ ! -f "$$dir/main.go" ]; then \
continue; \
fi; \
pkg=$${dir%/}; \
go build -o $(BUILDDIR)/$$pkg ./$$dir/main.go; \
done
.PHONY: test
test:
for bin in $(BUILDDIR)/*; do \
echo "\n"; \
$$bin; \
done; \
echo "\nAll Go examples executed.\n"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: all
all: build test clean
+11
View File
@@ -0,0 +1,11 @@
# how to
To build the Go examples in this directory, navigate to the specific example folder and run the following command:
```bash
make build ## 构建所有示例
make test ## 运行所有示例
make clean ## 清理构建产物
# 或者运行所有命令
make -s all
```
+14 -8
View File
@@ -17,7 +17,7 @@ type IPhone struct {
}
func (p *IPhone) setOS() {
fmt.Println("为该手机安装IOS系统")
fmt.Println(" 为该手机安装IOS系统")
}
// 具体产品:小米手机
@@ -26,7 +26,7 @@ type MiPhone struct {
}
func (p *MiPhone) setOS() {
fmt.Println("为该手机安装安卓系统")
fmt.Println(" 为该手机安装安卓系统")
}
// 抽象产品:笔记本电脑
@@ -40,7 +40,7 @@ type MacBook struct {
}
func (l *MacBook) setOS() {
fmt.Println("为该笔记本安装macOS系统")
fmt.Println(" 为该笔记本安装macOS系统")
}
// 具体产品:小米笔记本电脑
@@ -49,7 +49,7 @@ type MiLaptop struct {
}
func (l *MiLaptop) setOS() {
fmt.Println("为该笔记本安装Windows系统")
fmt.Println(" 为该笔记本安装Windows系统")
}
// 抽象工厂
@@ -93,20 +93,24 @@ func main() {
var phone Phone
var laptop Laptop
fmt.Println("======== 抽象工厂模式 ========")
// 选择苹果工厂
fmt.Println("伟哥选择了苹果工厂生产产品:")
factory = &AppleFactory{}
phone = factory.CreatePhone()
laptop = factory.CreateLaptop()
if iphone, ok := phone.(*IPhone); ok {
fmt.Printf("生产了一台%s手机\n", iphone.Brand)
fmt.Printf(" 生产了一台%s手机\n", iphone.Brand)
iphone.setOS()
}
if macbook, ok := laptop.(*MacBook); ok {
fmt.Printf("生产了一台%s笔记本电脑\n", macbook.Brand)
fmt.Printf(" 生产了一台%s笔记本电脑\n", macbook.Brand)
macbook.setOS()
}
fmt.Println()
fmt.Println("切换工厂生产其他品牌的产品...")
fmt.Println()
// 选择小米工厂
@@ -115,11 +119,13 @@ func main() {
phone = factory.CreatePhone()
laptop = factory.CreateLaptop()
if miPhone, ok := phone.(*MiPhone); ok {
fmt.Printf("生产了一台%s手机\n", miPhone.Brand)
fmt.Printf(" 生产了一台%s手机\n", miPhone.Brand)
miPhone.setOS()
}
if miLaptop, ok := laptop.(*MiLaptop); ok {
fmt.Printf("生产了一台%s笔记本电脑\n", miLaptop.Brand)
fmt.Printf(" 生产了一台%s笔记本电脑\n", miLaptop.Brand)
miLaptop.setOS()
}
fmt.Println("====== 抽象工厂模式结束 ======")
}