diff --git a/README.md b/README.md new file mode 100644 index 0000000..b256493 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# 《Go语言设计模式》配套代码 + + +#### ++++++++++++++++++++++++++++++++++++++++ +#### 《Go语言设计模式》源码 +#### ++++++++++++++++++++++++++++++++++++++++ +#### Author:廖显东(ShirDon) +#### Blog: https://www.shirdon.com/ +#### 作者微博:https://www.weibo.com/liaoxiandong +#### 作者知乎:https://www.zhihu.com/people/shirdonl +#### 仓库地址:https://gitee.com/shirdonl/goDesignPattern +#### 仓库地址:https://github.com/shirdonl/goDesignPattern +#### 交流咨询及反馈,请关注公众号"源码大数据" +#### ++++++++++++++++++++++++++++++++++++++++ + +# 图书展示 +图片名称 + +#### 作者图书购买链接如下: +https://search.jd.com/Search?keyword=%E5%BB%96%E6%98%BE%E4%B8%9C&qrst=1&psort=3&psort=3&pvid=d7fa99f63997446eb8d86f0ebb13febe&click=2 + +# 代码安装步骤如下: +#### 安装步骤如下: +#### (1)下载源码; +#### (2)解压; +#### (3)将解压的文件夹gitee.com或者github.com复制到$GOPATH/src目录下,如果gitee.com或者github.com目录已经存在,请将子目录shirdonl下的文件夹复制到gitee.com或者github.com目录中。 + +![qrcode](bookInfo/codebigdata.jpg) +#### 假如读者在阅读本书的过程中有任何疑问,请关注“源码大数据”公众号,并按照提示输入读者的问题,作者会尽快进行交流回复。 +#### 注意:开源仓库不包含第6章代码,要获取第6章源码,请购买本书通过前言的说明获取。 + + + + + + + diff --git a/bookInfo/bookPic1.png b/bookInfo/bookPic1.png new file mode 100644 index 0000000..04b76f2 Binary files /dev/null and b/bookInfo/bookPic1.png differ diff --git a/bookInfo/bookPic2.png b/bookInfo/bookPic2.png new file mode 100644 index 0000000..f8174a3 Binary files /dev/null and b/bookInfo/bookPic2.png differ diff --git a/bookInfo/codebigdata.jpg b/bookInfo/codebigdata.jpg new file mode 100644 index 0000000..1b25c4e Binary files /dev/null and b/bookInfo/codebigdata.jpg differ diff --git a/chapter2/.DS_Store b/chapter2/.DS_Store new file mode 100644 index 0000000..e0c8b8c Binary files /dev/null and b/chapter2/.DS_Store differ diff --git a/chapter2/abstractFactory/actualCombat/computer.go b/chapter2/abstractFactory/actualCombat/computer.go new file mode 100644 index 0000000..bc8a455 --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/computer.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//定义电脑接口 +type AbstractComputer interface { + SetColor(color string) + SetSize(size int) + GetColor() string + GetSize() int +} + +type Computer struct { + color string + size int +} + +func (s *Computer) SetColor(color string) { + s.color = color +} + +func (s *Computer) GetColor() string { + return s.color +} + +func (s *Computer) SetSize(size int) { + s.size = size +} + +func (s *Computer) GetSize() int { + return s.size +} diff --git a/chapter2/abstractFactory/actualCombat/interfaceElectronicFactory.go b/chapter2/abstractFactory/actualCombat/interfaceElectronicFactory.go new file mode 100644 index 0000000..c734d55 --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/interfaceElectronicFactory.go @@ -0,0 +1,32 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//电子产品工厂 +type InterfaceElectronicFactory interface { + MakePhone() AbstractPhone + MakeComputer() AbstractComputer +} + +//获取电子产品工厂对象 +func GetElectronicFactory(brand string) (InterfaceElectronicFactory, error) { + if brand == "Xiaomi" { + return &XiaomiFactory{}, nil + } + + if brand == "Lenovo" { + return &LenovoFactory{}, nil + } + + return nil, fmt.Errorf("%s", "error brand type") +} diff --git a/chapter2/abstractFactory/actualCombat/lenovo.go b/chapter2/abstractFactory/actualCombat/lenovo.go new file mode 100644 index 0000000..5c9edbb --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/lenovo.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//联想品牌工厂 +type LenovoFactory struct { +} + +//生产手机 +func (n *LenovoFactory) MakePhone() AbstractPhone { + return &LenovoPhone{ + Phone: Phone{ + color: "Black", + size: 5, + }, + } +} + +//生产电脑 +func (n *LenovoFactory) MakeComputer() AbstractComputer { + return &LenovoComputer{ + Computer: Computer{ + color: "White", + size: 14, + }, + } +} diff --git a/chapter2/abstractFactory/actualCombat/lenovoComputer.go b/chapter2/abstractFactory/actualCombat/lenovoComputer.go new file mode 100644 index 0000000..055385e --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/lenovoComputer.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//联想电脑 +type LenovoComputer struct { + Computer +} diff --git a/chapter2/abstractFactory/actualCombat/lenovoPhone.go b/chapter2/abstractFactory/actualCombat/lenovoPhone.go new file mode 100644 index 0000000..8123099 --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/lenovoPhone.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//联想手机 +type LenovoPhone struct { + Phone +} diff --git a/chapter2/abstractFactory/actualCombat/phone.go b/chapter2/abstractFactory/actualCombat/phone.go new file mode 100644 index 0000000..02e64f8 --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/phone.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//定义手机接口 +type AbstractPhone interface { + SetColor(color string) + SetSize(size int) + GetColor() string + GetSize() int +} + +type Phone struct { + color string + size int +} + +func (s *Phone) SetColor(color string) { + s.color = color +} + +func (s *Phone) GetColor() string { + return s.color +} + +func (s *Phone) SetSize(size int) { + s.size = size +} + +func (s *Phone) GetSize() int { + return s.size +} diff --git a/chapter2/abstractFactory/actualCombat/xiaomi.go b/chapter2/abstractFactory/actualCombat/xiaomi.go new file mode 100644 index 0000000..baba3d2 --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/xiaomi.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//小米品牌工厂 +type XiaomiFactory struct { +} + +//生产手机 +func (a *XiaomiFactory) MakePhone() AbstractPhone { + return &XiaomiPhone{ + Phone: Phone{ + color: "White", + size: 5, + }, + } +} + +//生产电脑 +func (a *XiaomiFactory) MakeComputer() AbstractComputer { + return &XiaomiComputer{ + Computer: Computer{ + color: "Black", + size: 14, + }, + } +} diff --git a/chapter2/abstractFactory/actualCombat/xiaomiComputer.go b/chapter2/abstractFactory/actualCombat/xiaomiComputer.go new file mode 100644 index 0000000..fdf396e --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/xiaomiComputer.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//小米电脑 +type XiaomiComputer struct { + Computer +} diff --git a/chapter2/abstractFactory/actualCombat/xiaomiPhone.go b/chapter2/abstractFactory/actualCombat/xiaomiPhone.go new file mode 100644 index 0000000..9f513a6 --- /dev/null +++ b/chapter2/abstractFactory/actualCombat/xiaomiPhone.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//小米手机 +type XiaomiPhone struct { + Phone +} diff --git a/chapter2/abstractFactory/example/abstractFactory.go b/chapter2/abstractFactory/example/abstractFactory.go new file mode 100644 index 0000000..aefa838 --- /dev/null +++ b/chapter2/abstractFactory/example/abstractFactory.go @@ -0,0 +1,48 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +// 抽象产品接口 +type AbstractProduct interface { + GetName() +} + +//具体产品 +type ConcreteProduct struct { +} + +//具体产品的方法 +func (c *ConcreteProduct) GetName() { + fmt.Println("具体产品 ConcreteProduct") +} + +// 抽象工厂接口 +type AbstractFactory interface { + CreateProduct() AbstractProduct +} + +//具体工厂 +type ConcreteFactory struct { +} + +// 初始化具体工厂对象 +func NewConcreteFactory() ConcreteFactory { + return ConcreteFactory{} +} + +//具体工厂创建具体产品 +func (s *ConcreteFactory) CreateProduct() ConcreteProduct { + return ConcreteProduct{} +} diff --git a/chapter2/abstractFactory/main-actual-combat.go b/chapter2/abstractFactory/main-actual-combat.go new file mode 100644 index 0000000..ec2e9b8 --- /dev/null +++ b/chapter2/abstractFactory/main-actual-combat.go @@ -0,0 +1,64 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/abstractFactory/actualCombat" +) + +func main() { + //声明小米工厂 + xiaomiFactory, _ := actualCombat.GetElectronicFactory("Xiaomi") + //声明联想工厂 + lenovoFactory, _ := actualCombat.GetElectronicFactory("Lenovo") + + //联想工厂生产联想手机 + lenovoPhone := lenovoFactory.MakePhone() + //联想电脑生产联想电脑 + lenovoComputer := lenovoFactory.MakeComputer() + + //小米工厂生产小米手机 + xiaomiPhone := xiaomiFactory.MakePhone() + //小米电脑生产小米电脑 + xiaomiComputer := xiaomiFactory.MakeComputer() + + printPhoneDetails(lenovoPhone) + printComputerDetails(lenovoComputer) + + printPhoneDetails(xiaomiPhone) + printComputerDetails(xiaomiComputer) +} + +func printPhoneDetails(s actualCombat.AbstractPhone) { + fmt.Printf("Color: %s", s.GetColor()) + fmt.Println() + fmt.Printf("Size: %d inch", s.GetSize()) + fmt.Println() +} + +func printComputerDetails(s actualCombat.AbstractComputer) { + fmt.Printf("Color: %s", s.GetColor()) + fmt.Println() + fmt.Printf("Size: %d inch", s.GetSize()) + fmt.Println() +} + +//$ go run main-actual-combat.go +//Color: Black +//Size: 5 inch +//Color: White +//Size: 14 inch +//Color: White +//Size: 5 inch +//Color: Black +//Size: 14 inch diff --git a/chapter2/abstractFactory/main.go b/chapter2/abstractFactory/main.go new file mode 100644 index 0000000..3e7132d --- /dev/null +++ b/chapter2/abstractFactory/main.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter2/abstractFactory/example" + +func main() { + factory := example.NewConcreteFactory() + product := factory.CreateProduct() + product.GetName() +} + +//$ go run main.go +//具体产品 ConcreteProduct diff --git a/chapter2/abstractFactory/pkg/interfaceComputer.go b/chapter2/abstractFactory/pkg/interfaceComputer.go new file mode 100644 index 0000000..b002d11 --- /dev/null +++ b/chapter2/abstractFactory/pkg/interfaceComputer.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//定义电脑接口 +type InterfaceComputer interface { + SetColor(color string) + SetSize(size int) + GetColor() string + GetSize() int +} + +type Computer struct { + color string + size int +} + +func (s *Computer) SetColor(color string) { + s.color = color +} + +func (s *Computer) GetColor() string { + return s.color +} + +func (s *Computer) SetSize(size int) { + s.size = size +} + +func (s *Computer) GetSize() int { + return s.size +} diff --git a/chapter2/abstractFactory/pkg/interfaceElectronicFactory.go b/chapter2/abstractFactory/pkg/interfaceElectronicFactory.go new file mode 100644 index 0000000..6a316c5 --- /dev/null +++ b/chapter2/abstractFactory/pkg/interfaceElectronicFactory.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//电子产品工厂 +type InterfaceElectronicFactory interface { + MakePhone() InterfacePhone + MakeComputer() InterfaceComputer +} + +//获取电子产品工厂 +func GetElectronicFactory(brand string) (InterfaceElectronicFactory, error) { + if brand == "Xiaomi" { + return &Xiaomi{}, nil + } + + if brand == "Lenovo" { + return &Lenovo{}, nil + } + + return nil, fmt.Errorf("%s", "error brand type") +} diff --git a/chapter2/abstractFactory/pkg/interfacePhone.go b/chapter2/abstractFactory/pkg/interfacePhone.go new file mode 100644 index 0000000..74d33e7 --- /dev/null +++ b/chapter2/abstractFactory/pkg/interfacePhone.go @@ -0,0 +1,41 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//定义手机接口 +type InterfacePhone interface { + SetColor(color string) + SetSize(size int) + GetColor() string + GetSize() int +} + +type Phone struct { + color string + size int +} + +func (s *Phone) SetColor(color string) { + s.color = color +} + +func (s *Phone) GetColor() string { + return s.color +} + +func (s *Phone) SetSize(size int) { + s.size = size +} + +func (s *Phone) GetSize() int { + return s.size +} diff --git a/chapter2/abstractFactory/pkg/lenovo.go b/chapter2/abstractFactory/pkg/lenovo.go new file mode 100644 index 0000000..0e4d9bc --- /dev/null +++ b/chapter2/abstractFactory/pkg/lenovo.go @@ -0,0 +1,36 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//联想品牌工厂 +type Lenovo struct { +} + +//生产手机 +func (n *Lenovo) MakePhone() InterfacePhone { + return &LenovoPhone{ + Phone: Phone{ + color: "Black", + size: 5, + }, + } +} + +//生产电脑 +func (n *Lenovo) MakeComputer() InterfaceComputer { + return &LenovoComputer{ + Computer: Computer{ + color: "White", + size: 14, + }, + } +} diff --git a/chapter2/abstractFactory/pkg/lenovoComputer.go b/chapter2/abstractFactory/pkg/lenovoComputer.go new file mode 100644 index 0000000..8ebf4a8 --- /dev/null +++ b/chapter2/abstractFactory/pkg/lenovoComputer.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//联想电脑 +type LenovoComputer struct { + Computer +} diff --git a/chapter2/abstractFactory/pkg/lenovoPhone.go b/chapter2/abstractFactory/pkg/lenovoPhone.go new file mode 100644 index 0000000..8cc9462 --- /dev/null +++ b/chapter2/abstractFactory/pkg/lenovoPhone.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//联想手机 +type LenovoPhone struct { + Phone +} diff --git a/chapter2/abstractFactory/pkg/xiaomi.go b/chapter2/abstractFactory/pkg/xiaomi.go new file mode 100644 index 0000000..9f0bbe2 --- /dev/null +++ b/chapter2/abstractFactory/pkg/xiaomi.go @@ -0,0 +1,36 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//小米品牌工厂 +type Xiaomi struct { +} + +//生产手机 +func (a *Xiaomi) MakePhone() InterfacePhone { + return &XiaomiPhone{ + Phone: Phone{ + color: "Xiaomi", + size: 5, + }, + } +} + +//生产电脑 +func (a *Xiaomi) MakeComputer() InterfaceComputer { + return &XiaomiComputer{ + Computer: Computer{ + color: "Xiaomi", + size: 14, + }, + } +} diff --git a/chapter2/abstractFactory/pkg/xiaomiComputer.go b/chapter2/abstractFactory/pkg/xiaomiComputer.go new file mode 100644 index 0000000..7369530 --- /dev/null +++ b/chapter2/abstractFactory/pkg/xiaomiComputer.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//小米电脑 +type XiaomiComputer struct { + Computer +} diff --git a/chapter2/abstractFactory/pkg/xiaomiPhone.go b/chapter2/abstractFactory/pkg/xiaomiPhone.go new file mode 100644 index 0000000..1f5eb02 --- /dev/null +++ b/chapter2/abstractFactory/pkg/xiaomiPhone.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//小米手机 +type XiaomiPhone struct { + Phone +} diff --git a/chapter2/builder/actualCombat/car.go b/chapter2/builder/actualCombat/car.go new file mode 100644 index 0000000..18544c7 --- /dev/null +++ b/chapter2/builder/actualCombat/car.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Car struct { + SeatsType string + EngineType string + Number int +} diff --git a/chapter2/builder/actualCombat/director.go b/chapter2/builder/actualCombat/director.go new file mode 100644 index 0000000..76f1899 --- /dev/null +++ b/chapter2/builder/actualCombat/director.go @@ -0,0 +1,34 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//主管类型 +type Director struct { + Builder InterfaceBuilder +} + +func NewDirector(b InterfaceBuilder) *Director { + return &Director{ + Builder: b, + } +} + +func (d *Director) SetBuilder(b InterfaceBuilder) { + d.Builder = b +} + +func (d *Director) BuildCar() Car { + d.Builder.SetEngineType() + d.Builder.SetSeatsType() + d.Builder.SetNumber() + return d.Builder.GetCar() +} diff --git a/chapter2/builder/actualCombat/interfaceBuilder.go b/chapter2/builder/actualCombat/interfaceBuilder.go new file mode 100644 index 0000000..3cd7d2c --- /dev/null +++ b/chapter2/builder/actualCombat/interfaceBuilder.go @@ -0,0 +1,32 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//生成器接口 +type InterfaceBuilder interface { + SetSeatsType() + SetEngineType() + SetNumber() + GetCar() Car +} + +//获取生成器 +func GetBuilder(BuilderType string) InterfaceBuilder { + if BuilderType == "mpv" { + return &MpvBuilder{} + } + + if BuilderType == "suv" { + return &SuvBuilder{} + } + return nil +} diff --git a/chapter2/builder/actualCombat/mpvBuilder.go b/chapter2/builder/actualCombat/mpvBuilder.go new file mode 100644 index 0000000..e6eaac3 --- /dev/null +++ b/chapter2/builder/actualCombat/mpvBuilder.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//MPV生成器 +type MpvBuilder struct { + SeatsType string + EngineType string + Number int +} + +func NewMpvBuilder() *MpvBuilder { + return &MpvBuilder{} +} + +func (b *MpvBuilder) SetSeatsType() { + b.SeatsType = "MPV型座椅" +} + +func (b *MpvBuilder) SetEngineType() { + b.EngineType = "MPV型引擎" +} + +func (b *MpvBuilder) SetNumber() { + b.Number = 8 +} + +func (b *MpvBuilder) GetCar() Car { + return Car{ + EngineType: b.EngineType, + SeatsType: b.SeatsType, + Number: b.Number, + } +} diff --git a/chapter2/builder/actualCombat/suvBuilder.go b/chapter2/builder/actualCombat/suvBuilder.go new file mode 100644 index 0000000..e311d64 --- /dev/null +++ b/chapter2/builder/actualCombat/suvBuilder.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//SUV生成器 +type SuvBuilder struct { + SeatsType string + EngineType string + Number int +} + +func newSuvBuilder() *SuvBuilder { + return &SuvBuilder{} +} + +func (b *SuvBuilder) SetSeatsType() { + b.SeatsType = "SUV型座椅" +} + +func (b *SuvBuilder) SetEngineType() { + b.EngineType = "SUV型引擎" +} + +func (b *SuvBuilder) SetNumber() { + b.Number = 6 +} + +func (b *SuvBuilder) GetCar() Car { + return Car{ + EngineType: b.EngineType, + SeatsType: b.SeatsType, + Number: b.Number, + } +} diff --git a/chapter2/builder/example/builder.go b/chapter2/builder/example/builder.go new file mode 100644 index 0000000..e4b29b7 --- /dev/null +++ b/chapter2/builder/example/builder.go @@ -0,0 +1,57 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +// 主管 +type Director struct { + builder Builder +} + +// 初始化主管对象 +func NewDirector(builder Builder) Director { + return Director{builder} +} + +// 通过一系列步骤生成产品 +func (d *Director) Construct() { + d.builder.Build() +} + +// 生成器接口 +type Builder interface { + Build() +} + +//具体生成器,用于构建产品的生成器 +type ConcreteBuilder struct { + result Product +} + +// 初始化具体生成器对象 +func NewConcreteBuilder() ConcreteBuilder { + return ConcreteBuilder{result: Product{}} +} + +// 生成产品 +func (b *ConcreteBuilder) Build() { + b.result = Product{} +} + +// 返回在生成步骤中生成的产品 +func (b *ConcreteBuilder) GetResult() Product { + return Product{true} +} + +// 产品 +type Product struct { + Built bool +} diff --git a/chapter2/builder/main-actual-combat.go b/chapter2/builder/main-actual-combat.go new file mode 100644 index 0000000..46c270e --- /dev/null +++ b/chapter2/builder/main-actual-combat.go @@ -0,0 +1,51 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/builder/actualCombat" +) + +func main() { + //声明MPV生成器对象 + MpvBuilder := actualCombat.GetBuilder("mpv") + //声明SUV生成器对象 + SuvBuilder := actualCombat.GetBuilder("suv") + + //声明主管对象 + Director := actualCombat.NewDirector(MpvBuilder) + //生产MPV类型汽车 + mpvCar := Director.BuildCar() + + fmt.Printf("MPV类型引擎: %s\n", mpvCar.EngineType) + fmt.Printf("MPV类型座椅: %s\n", mpvCar.SeatsType) + fmt.Printf("MPV类型数量: %d\n", mpvCar.Number) + + //设置生成器对象 + Director.SetBuilder(SuvBuilder) + //生产SUV类型汽车 + suvCar := Director.BuildCar() + + fmt.Printf("\nSUV类型引擎: %s\n", suvCar.EngineType) + fmt.Printf("SUV类型座椅: %s\n", suvCar.SeatsType) + fmt.Printf("SUV类型数量: %d\n", suvCar.Number) +} + +//$ go run main-actual-combat.go +//MPV类型引擎: MPV型引擎 +//MPV类型座椅: MPV型座椅 +//MPV类型数量: 8 +// +//SUV类型引擎: SUV型引擎 +//SUV类型座椅: SUV型座椅 +//SUV类型数量: 6 diff --git a/chapter2/builder/main.go b/chapter2/builder/main.go new file mode 100644 index 0000000..cd6e3f2 --- /dev/null +++ b/chapter2/builder/main.go @@ -0,0 +1,42 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/builder/pkg" +) + +func main() { + //声明Mpv生成器 + MpvBuilder := pkg.GetBuilder("mpv") + //声明Mpv生成器 + SuvBuilder := pkg.GetBuilder("suv") + + //声明主管 + Director := pkg.NewDirector(MpvBuilder) + //生产汽车 + mpvCar := Director.BuildCar() + + fmt.Printf("MPV类型引擎: %s\n", mpvCar.EngineType) + fmt.Printf("MPV类型座椅: %s\n", mpvCar.SeatsType) + fmt.Printf("MPV类型数量: %d\n", mpvCar.Number) + + //声明主管 + Director.SetBuilder(SuvBuilder) + //生产汽车 + suvCar := Director.BuildCar() + + fmt.Printf("\nSUV类型引擎: %s\n", suvCar.EngineType) + fmt.Printf("SUV类型座椅: %s\n", suvCar.SeatsType) + fmt.Printf("SUV类型数量: %d\n", suvCar.Number) +} diff --git a/chapter2/builder/pkg/car.go b/chapter2/builder/pkg/car.go new file mode 100644 index 0000000..129b47b --- /dev/null +++ b/chapter2/builder/pkg/car.go @@ -0,0 +1,19 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type Car struct { + SeatsType string + EngineType string + Number int +} + diff --git a/chapter2/builder/pkg/director.go b/chapter2/builder/pkg/director.go new file mode 100644 index 0000000..d4982b6 --- /dev/null +++ b/chapter2/builder/pkg/director.go @@ -0,0 +1,34 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//主管类型 +type Director struct { + Builder InterfaceBuilder +} + +func NewDirector(b InterfaceBuilder) *Director { + return &Director{ + Builder: b, + } +} + +func (d *Director) SetBuilder(b InterfaceBuilder) { + d.Builder = b +} + +func (d *Director) BuildCar() Car { + d.Builder.SetEngineType() + d.Builder.SetSeatsType() + d.Builder.SetNumber() + return d.Builder.GetCar() +} \ No newline at end of file diff --git a/chapter2/builder/pkg/interfaceBuilder.go b/chapter2/builder/pkg/interfaceBuilder.go new file mode 100644 index 0000000..27d47ab --- /dev/null +++ b/chapter2/builder/pkg/interfaceBuilder.go @@ -0,0 +1,32 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//生成器接口 +type InterfaceBuilder interface { + SetSeatsType() + SetEngineType() + SetNumber() + GetCar() Car +} + +//获取生成器 +func GetBuilder(BuilderType string) InterfaceBuilder { + if BuilderType == "mpv" { + return &MpvBuilder{} + } + + if BuilderType == "suv" { + return &SuvBuilder{} + } + return nil +} \ No newline at end of file diff --git a/chapter2/builder/pkg/mpvBuilder.go b/chapter2/builder/pkg/mpvBuilder.go new file mode 100644 index 0000000..f4cfbdd --- /dev/null +++ b/chapter2/builder/pkg/mpvBuilder.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//MPV生成器 +type MpvBuilder struct { + SeatsType string + EngineType string + Number int +} + +func NewMpvBuilder() *MpvBuilder { + return &MpvBuilder{} +} + +func (b *MpvBuilder) SetSeatsType() { + b.SeatsType = "MPV型座椅" +} + +func (b *MpvBuilder) SetEngineType() { + b.EngineType = "MPV型引擎" +} + +func (b *MpvBuilder) SetNumber() { + b.Number = 8 +} + +func (b *MpvBuilder) GetCar() Car { + return Car{ + EngineType: b.EngineType, + SeatsType: b.SeatsType, + Number: b.Number, + } +} diff --git a/chapter2/builder/pkg/suvBuilder.go b/chapter2/builder/pkg/suvBuilder.go new file mode 100644 index 0000000..c4a34c8 --- /dev/null +++ b/chapter2/builder/pkg/suvBuilder.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//SUV生成器 +type SuvBuilder struct { + SeatsType string + EngineType string + Number int +} + +func newSuvBuilder() *SuvBuilder { + return &SuvBuilder{} +} + +func (b *SuvBuilder) SetSeatsType() { + b.SeatsType = "SUV型座椅" +} + +func (b *SuvBuilder) SetEngineType() { + b.EngineType = "SUV型引擎" +} + +func (b *SuvBuilder) SetNumber() { + b.Number = 6 +} + +func (b *SuvBuilder) GetCar() Car { + return Car{ + EngineType: b.EngineType, + SeatsType: b.SeatsType, + Number: b.Number, + } +} diff --git a/chapter2/factory/actualCombat/anta.go b/chapter2/factory/actualCombat/anta.go new file mode 100644 index 0000000..da102f6 --- /dev/null +++ b/chapter2/factory/actualCombat/anta.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type ANTA struct { + clothes +} + +func newANTA() IClothes { + return &ANTA{ + clothes: clothes{ + name: "ANTA clothes", + size: 4, + }, + } +} diff --git a/chapter2/factory/actualCombat/clothes.go b/chapter2/factory/actualCombat/clothes.go new file mode 100644 index 0000000..1fb4ec1 --- /dev/null +++ b/chapter2/factory/actualCombat/clothes.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type clothes struct { + name string + size int +} + +func (c *clothes) setName(name string) { + c.name = name +} + +func (c *clothes) GetName() string { + return c.name +} + +func (c *clothes) setSize(size int) { + c.size = size +} + +func (c *clothes) GetSize() int { + return c.size +} diff --git a/chapter2/factory/actualCombat/clothesFactory.go b/chapter2/factory/actualCombat/clothesFactory.go new file mode 100644 index 0000000..4529423 --- /dev/null +++ b/chapter2/factory/actualCombat/clothesFactory.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +func MakeClothes(clothesType string) (IClothes, error) { + if clothesType == "ANTA" { + return newANTA(), nil + } + if clothesType == "PEAK" { + return newPEAK(), nil + } + return nil, fmt.Errorf("Wrong clothes type passed") +} diff --git a/chapter2/factory/actualCombat/iClothes.go b/chapter2/factory/actualCombat/iClothes.go new file mode 100644 index 0000000..bb95c97 --- /dev/null +++ b/chapter2/factory/actualCombat/iClothes.go @@ -0,0 +1,19 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type IClothes interface { + setName(name string) + setSize(size int) + GetName() string + GetSize() int +} diff --git a/chapter2/factory/actualCombat/peak.go b/chapter2/factory/actualCombat/peak.go new file mode 100644 index 0000000..efb3981 --- /dev/null +++ b/chapter2/factory/actualCombat/peak.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type PEAK struct { + clothes +} + +func newPEAK() IClothes { + return &PEAK{ + clothes: clothes{ + name: "PEAK clothes", + size: 1, + }, + } +} diff --git a/chapter2/factory/example/factoryMethod.go b/chapter2/factory/example/factoryMethod.go new file mode 100644 index 0000000..64778ea --- /dev/null +++ b/chapter2/factory/example/factoryMethod.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +// 工厂接口 +type Factory interface { + FactoryMethod(owner string) Product +} + +// 具体工厂 +type ConcreteFactory struct { +} + +// 具体工厂的工厂方法 +func (cf *ConcreteFactory) FactoryMethod(owner string) Product { + p := &ConcreteProduct{} + return p +} + +// 产品 +type Product interface { + Use() +} + +//具体产品 +type ConcreteProduct struct { +} + +//具体产品的方法 +func (p *ConcreteProduct) Use() { + fmt.Println("This is a concrete product") +} diff --git a/chapter2/factory/main-actual-combat.go b/chapter2/factory/main-actual-combat.go new file mode 100644 index 0000000..d328e02 --- /dev/null +++ b/chapter2/factory/main-actual-combat.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/factory/actualCombat" +) + +func main() { + ANTA, _ := actualCombat.MakeClothes("ANTA") + PEAK, _ := actualCombat.MakeClothes("PEAK") + + printDetails(ANTA) + printDetails(PEAK) +} + +func printDetails(c actualCombat.IClothes) { + fmt.Printf("Clothes: %s", c.GetName()) + fmt.Println() + fmt.Printf("Size: %d", c.GetSize()) + fmt.Println() +} + +//$ go run main-actual-combat.go +//Clothes: ANTA clothes +//Size: 4 +//Clothes: PEAK clothes +//Size: 1 diff --git a/chapter2/factory/main.go b/chapter2/factory/main.go new file mode 100644 index 0000000..1d6efae --- /dev/null +++ b/chapter2/factory/main.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/factory/pkg" +) + +func main() { + ANTA, _ := pkg.MakeClothes("ANTA") + PEAK, _ := pkg.MakeClothes("PEAK") + + printDetails(ANTA) + printDetails(PEAK) +} + +func printDetails(c pkg.IClothes) { + fmt.Printf("Clothes: %s", c.GetName()) + fmt.Println() + fmt.Printf("Size: %d", c.GetSize()) + fmt.Println() +} + +//Clothes: ANTA clothes +//Size: 4 +//Clothes: PEAK clothes +//Size: 1 diff --git a/chapter2/factory/pkg/adidas.go b/chapter2/factory/pkg/adidas.go new file mode 100644 index 0000000..7a39665 --- /dev/null +++ b/chapter2/factory/pkg/adidas.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type PEAK struct { + clothes +} + +func newPEAK() IClothes { + return &PEAK{ + clothes: clothes{ + name: "PEAK clothes", + size: 1, + }, + } +} diff --git a/chapter2/factory/pkg/clothes.go b/chapter2/factory/pkg/clothes.go new file mode 100644 index 0000000..ea146ab --- /dev/null +++ b/chapter2/factory/pkg/clothes.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type clothes struct { + name string + size int +} + +func (c *clothes) setName(name string) { + c.name = name +} + +func (c *clothes) GetName() string { + return c.name +} + +func (c *clothes) setSize(size int) { + c.size = size +} + +func (c *clothes) GetSize() int { + return c.size +} \ No newline at end of file diff --git a/chapter2/factory/pkg/clothesFactory.go b/chapter2/factory/pkg/clothesFactory.go new file mode 100644 index 0000000..190ae13 --- /dev/null +++ b/chapter2/factory/pkg/clothesFactory.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +func MakeClothes(clothesType string) (IClothes, error) { + if clothesType == "ANTA" { + return newANTA(), nil + } + if clothesType == "PEAK" { + return newPEAK(), nil + } + return nil, fmt.Errorf("Wrong clothes type passed") +} diff --git a/chapter2/factory/pkg/iClothes.go b/chapter2/factory/pkg/iClothes.go new file mode 100644 index 0000000..bf2b73e --- /dev/null +++ b/chapter2/factory/pkg/iClothes.go @@ -0,0 +1,19 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type IClothes interface { + setName(name string) + setSize(size int) + GetName() string + GetSize() int +} diff --git a/chapter2/factory/pkg/nike.go b/chapter2/factory/pkg/nike.go new file mode 100644 index 0000000..2d0145c --- /dev/null +++ b/chapter2/factory/pkg/nike.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type ANTA struct { + clothes +} + +func newANTA() IClothes { + return &ANTA{ + clothes: clothes{ + name: "ANTA clothes", + size: 4, + }, + } +} diff --git a/chapter2/objectPool/actualCombat/objectPoolResource.go b/chapter2/objectPool/actualCombat/objectPoolResource.go new file mode 100644 index 0000000..4276fb0 --- /dev/null +++ b/chapter2/objectPool/actualCombat/objectPoolResource.go @@ -0,0 +1,82 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import ( + "errors" + "log" + "math/rand" + "sync" + "time" +) + +const getResMaxTime = 3 * time.Second + +var ( + ErrPoolNotExist = errors.New("pool not exist") + ErrGetResTimeout = errors.New("get resource time out") +) + +//资源类 +type Resource struct { + reusable int +} + +//初始化资源对象 +//模拟缓慢的资源访问,例如,TCP 连接等 +func NewResource(id int) *Resource { + time.Sleep(500 * time.Millisecond) + return &Resource{reusable: id} +} + +//模拟资源耗时 +func (r *Resource) Do(workId int) { + time.Sleep(time.Duration(rand.Intn(5)) * 100 * time.Millisecond) + log.Printf("using resource #%d finished work %d finish\n", r.reusable, workId) +} + +//对象池 +type Pool chan *Resource + +//并发创建资源对象,节省资源对象初始化时间 +func New(size int) Pool { + p := make(Pool, size) + wg := new(sync.WaitGroup) + wg.Add(size) + for i := 0; i < size; i++ { + go func(reusable int) { + p <- NewResource(reusable) + wg.Done() + }(i) + } + wg.Wait() + return p +} + +//从获取对象池获取对象 +func (p Pool) GetResource() (r *Resource, err error) { + select { + case r := <-p: + return r, nil + case <-time.After(getResMaxTime): + return nil, ErrGetResTimeout + } +} + +//将资源返回到资源池 +func (p Pool) GiveBackResource(r *Resource) error { + if p == nil { + return ErrPoolNotExist + } + p <- r + return nil +} diff --git a/chapter2/objectPool/example/objectPool.go b/chapter2/objectPool/example/objectPool.go new file mode 100644 index 0000000..2707c17 --- /dev/null +++ b/chapter2/objectPool/example/objectPool.go @@ -0,0 +1,59 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "sync" +) + +// 对象池 +type Pool struct { + sync.Mutex + Inuse []interface{} + Available []interface{} + new func() interface{} +} + +// 创建一个新对象池 +func NewPool(new func() interface{}) *Pool { + return &Pool{new: new} +} + +// 从池中获取要使用的新池对象。 +// 如果没有可用,则获取创建1个池对象的新实例 +func (p *Pool) Acquire() interface{} { + p.Lock() + var object interface{} + if len(p.Available) != 0 { + object = p.Available[0] + p.Available = append(p.Available[:0], p.Available[1:]...) + p.Inuse = append(p.Inuse, object) + } else { + object = p.new() + p.Inuse = append(p.Inuse, object) + } + p.Unlock() + return object +} + +// 将对象释放回对象池 +func (p *Pool) Release(object interface{}) { + p.Lock() + p.Available = append(p.Available, object) + for i, v := range p.Inuse { + if v == object { + p.Inuse = append(p.Inuse[:i], p.Inuse[i+1:]...) + break + } + } + p.Unlock() +} diff --git a/chapter2/objectPool/main-actual-combat.go b/chapter2/objectPool/main-actual-combat.go new file mode 100644 index 0000000..8928ea4 --- /dev/null +++ b/chapter2/objectPool/main-actual-combat.go @@ -0,0 +1,59 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter2/objectPool/actualCombat" + "log" + "sync" +) + +func main() { + // 初始化一个包含五个资源的资源池 + // 可以调整为 1 或 10 以查看差异 + size := 5 + p := actualCombat.New(size) + + // 调用资源池 + doWork := func(workId int, wg *sync.WaitGroup) { + defer wg.Done() + // 从资源池中获取资源对象 + res, err := p.GetResource() + if err != nil { + log.Println(err) + return + } + //返回的资源对象 + defer p.GiveBackResource(res) + // 使用资源处理工作 + res.Do(workId) + } + + // 模拟100个并发进程从资产池中获取资源对象 + num := 100 + wg := new(sync.WaitGroup) + wg.Add(num) + for i := 0; i < num; i++ { + go doWork(i, wg) + } + wg.Wait() +} + +//$ go run main-actual-combat.go +//2022/06/04 16:38:39 using resource #1 finished work 3 finish +//2022/06/04 16:38:39 using resource #0 finished work 5 finish +//2022/06/04 16:38:39 using resource #0 finished work 8 finish +//2022/06/04 16:38:39 using resource #0 finished work 12 finish +//2022/06/04 16:38:39 using resource #3 finished work 9 finish +//2022/06/04 16:38:39 using resource #3 finished work 11 finish +//2022/06/04 16:38:39 using resource #2 finished work 1 finish +//...省略更多记录 diff --git a/chapter2/objectPool/main.go b/chapter2/objectPool/main.go new file mode 100644 index 0000000..da81fdc --- /dev/null +++ b/chapter2/objectPool/main.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/objectPool/example" +) + +func main() { + num := func() interface{} { + return 10.0 + } + pool := example.NewPool(num) + object := pool.Acquire() + + fmt.Println(pool.Inuse) + fmt.Println(pool.Available) + + pool.Release(object) + fmt.Println(pool.Inuse) + fmt.Println(pool.Available) +} + +//$ go run main.go +//[10] +//[] +//[] +//[10] diff --git a/chapter2/prototype/actualCombat/file.go b/chapter2/prototype/actualCombat/file.go new file mode 100644 index 0000000..1018626 --- /dev/null +++ b/chapter2/prototype/actualCombat/file.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//文件类型 +type File struct { + Name string +} + +//打印 +func (f *File) Print(indentation string) { + fmt.Println(indentation + f.Name) +} + +//克隆 +func (f *File) Clone() InterfaceNode { + return &File{Name: f.Name + "_Clone"} +} diff --git a/chapter2/prototype/actualCombat/folder.go b/chapter2/prototype/actualCombat/folder.go new file mode 100644 index 0000000..eb3cf3a --- /dev/null +++ b/chapter2/prototype/actualCombat/folder.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//文件夹 +type Folder struct { + Children []InterfaceNode + Name string +} + +//打印 +func (f *Folder) Print(indentation string) { + fmt.Println(indentation + f.Name) + for _, i := range f.Children { + i.Print(indentation + indentation) + } +} + +//克隆 +func (f *Folder) Clone() InterfaceNode { + CloneFolder := &Folder{Name: f.Name + "_Clone"} + var tempChildren []InterfaceNode + for _, i := range f.Children { + copy := i.Clone() + tempChildren = append(tempChildren, copy) + } + CloneFolder.Children = tempChildren + return CloneFolder +} diff --git a/chapter2/prototype/actualCombat/interfaceNode.go b/chapter2/prototype/actualCombat/interfaceNode.go new file mode 100644 index 0000000..7920be3 --- /dev/null +++ b/chapter2/prototype/actualCombat/interfaceNode.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//节点接口 +type InterfaceNode interface { + Print(string) + Clone() InterfaceNode +} diff --git a/chapter2/prototype/example/prototype.go b/chapter2/prototype/example/prototype.go new file mode 100644 index 0000000..ceef1d5 --- /dev/null +++ b/chapter2/prototype/example/prototype.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +// 原型接口 +type Prototype interface { + GetName() string + Clone() Prototype +} + +// 具体原型类 +type ConcretePrototype struct { + Name string +} + +// 返回具体原型的名称 +func (p *ConcretePrototype) GetName() string { + return p.Name +} + +// Clone 创建一个ConcretePrototype类的克隆新实例 +func (p *ConcretePrototype) Clone() Prototype { + return &ConcretePrototype{p.Name} +} diff --git a/chapter2/prototype/main-actual-combat.go b/chapter2/prototype/main-actual-combat.go new file mode 100644 index 0000000..8390eff --- /dev/null +++ b/chapter2/prototype/main-actual-combat.go @@ -0,0 +1,60 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/prototype/actualCombat" +) + +func main() { + //声明文件对象File1 + File1 := &actualCombat.File{Name: "File1"} + //声明文件对象File2 + File2 := &actualCombat.File{Name: "File2"} + //声明文件对象File3 + File3 := &actualCombat.File{Name: "File3"} + + //声明文件夹对象Folder1 + Folder1 := &actualCombat.Folder{ + Children: []actualCombat.InterfaceNode{File1}, + Name: "文件夹Folder1", + } + + //声明文件夹对象Folder2 + Folder2 := &actualCombat.Folder{ + Children: []actualCombat.InterfaceNode{Folder1, File2, File3}, + Name: "文件夹Folder2", + } + fmt.Println("\n打印文件夹Folder2的层级:") + Folder2.Print(" ") + + CloneFolder := Folder2.Clone() + fmt.Println("\n打印复制文件夹Folder2的层级:") + CloneFolder.Print(" ") +} + +//$ go run main-actual-combat.go +// +//打印文件夹Folder2的层级: +// 文件夹Folder2 +// 文件夹Folder1 +// File1 +// File2 +// File3 +// +//打印复制文件夹Folder2的层级: +// 文件夹Folder2_Clone +// 文件夹Folder1_Clone +// File1_Clone +// File2_Clone +// File3_Clone diff --git a/chapter2/prototype/main.go b/chapter2/prototype/main.go new file mode 100644 index 0000000..ad0236e --- /dev/null +++ b/chapter2/prototype/main.go @@ -0,0 +1,27 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/prototype/example" +) + +func main() { + cp := &example.ConcretePrototype{Name: "Shirdon"} + cp.Clone() + res := cp.GetName() + fmt.Println(res) +} + +//$ go run main.go +//Shirdon diff --git a/chapter2/prototype/pkg/file.go b/chapter2/prototype/pkg/file.go new file mode 100644 index 0000000..0189510 --- /dev/null +++ b/chapter2/prototype/pkg/file.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//文件类型 +type File struct { + Name string +} + +//打印 +func (f *File) Print(indentation string) { + fmt.Println(indentation + f.Name) +} + +//克隆 +func (f *File) Clone() InterfaceNode { + return &File{Name: f.Name + "_Clone"} +} diff --git a/chapter2/prototype/pkg/folder.go b/chapter2/prototype/pkg/folder.go new file mode 100644 index 0000000..96c6fc0 --- /dev/null +++ b/chapter2/prototype/pkg/folder.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//文件夹 +type Folder struct { + Children []InterfaceNode + Name string +} + +//打印 +func (f *Folder) Print(indentation string) { + fmt.Println(indentation + f.Name) + for _, i := range f.Children { + i.Print(indentation + indentation) + } +} + +//克隆 +func (f *Folder) Clone() InterfaceNode { + CloneFolder := &Folder{Name: f.Name + "_Clone"} + var tempChildren []InterfaceNode + for _, i := range f.Children { + copy := i.Clone() + tempChildren = append(tempChildren, copy) + } + CloneFolder.Children = tempChildren + return CloneFolder +} diff --git a/chapter2/prototype/pkg/interfaceNode.go b/chapter2/prototype/pkg/interfaceNode.go new file mode 100644 index 0000000..7a18ccc --- /dev/null +++ b/chapter2/prototype/pkg/interfaceNode.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//节点接口 +type InterfaceNode interface { + Print(string) + Clone() InterfaceNode +} diff --git a/chapter2/single/actualCombat/singleton.go b/chapter2/single/actualCombat/singleton.go new file mode 100644 index 0000000..32ecff1 --- /dev/null +++ b/chapter2/single/actualCombat/singleton.go @@ -0,0 +1,42 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import ( + "fmt" + "sync" +) + +var lock = &sync.Mutex{} + +type singleton struct { +} + +var instance *singleton + +//获取实例 +func GetInstance() *singleton { + if instance == nil { + lock.Lock() + defer lock.Unlock() + if instance == nil { + fmt.Println("创建单个实例") + instance = new(singleton) + } else { + fmt.Println("已创建单个实例!") + } + } else { + fmt.Println("已创建单个实例!") + } + + return instance +} diff --git a/chapter2/single/example/singleton1.go b/chapter2/single/example/singleton1.go new file mode 100644 index 0000000..f53b8de --- /dev/null +++ b/chapter2/single/example/singleton1.go @@ -0,0 +1,83 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "sync" +) + +//单例类 +type singleton struct { + value int +} + +//声明私有变量 +var instance *singleton + +// +// +////声明私有变量 +//var instance *singleton +////获取单例对象 +//func GetInstance() *singleton { +// if instance == nil { +// instance = new(singleton) +// } +// return instance +//} +// +////声明私有变量 +//var instance *singleton +// +////声明锁对象 +//var mutex sync.Mutex +////加锁保证协程安全 +//func GetInstance() *singleton { +// mutex.Lock() +// defer mutex.Unlock() +// if instance == nil { +// instance = new(singleton) +// } +// return instance +//} + +////声明锁对象 +//var mutex sync.Mutex +////当对象为空时,对对象加锁,当创建好对象后,获取对象时就不用加锁了 +//func GetInstance() *singleton { +// if instance == nil { +// mutex.Lock() +// if instance == nil { +// instance = new(singleton) +// fmt.Println("创建单个实例") +// } +// mutex.Unlock() +// } +// return instance +//} + +var once sync.Once + +func GetInstance() *singleton { + once.Do(func() { + instance = new(singleton) + fmt.Println("创建单个实例") + }) + return instance +} + +func main() { + for i := 0; i < 3; i++ { + GetInstance() + } +} diff --git a/chapter2/single/example/singleton2.go b/chapter2/single/example/singleton2.go new file mode 100644 index 0000000..931ea3b --- /dev/null +++ b/chapter2/single/example/singleton2.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "fmt" + +type singleton struct { +} + +var instance *singleton + +func init() { + if instance == nil { + instance = new(singleton) + fmt.Println("创建单个实例") + } +} + +// 提供获取实例的方法 +func GetInstance() *singleton { + return instance +} + +func main() { + for i := 0; i < 3; i++ { + GetInstance() + } +} diff --git a/chapter2/single/main-actual-combat.go b/chapter2/single/main-actual-combat.go new file mode 100644 index 0000000..7149a26 --- /dev/null +++ b/chapter2/single/main-actual-combat.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/single/actualCombat" +) + +func main() { + for i := 0; i < 3; i++ { + go actualCombat.GetInstance() + } + + fmt.Scanln() +} + +//创建单个实例 +//已创建单个实例! +//已创建单个实例! diff --git a/chapter2/single/main.go b/chapter2/single/main.go new file mode 100644 index 0000000..3a75a8b --- /dev/null +++ b/chapter2/single/main.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter2/single/pkg" +) + +func main() { + for i := 0; i < 3; i++ { + go pkg.GetInstance() + } + + fmt.Scanln() +} + +//创建单个实例 +//已创建单个实例! +//已创建单个实例! diff --git a/chapter2/single/pkg/singleton.go b/chapter2/single/pkg/singleton.go new file mode 100644 index 0000000..b2efce3 --- /dev/null +++ b/chapter2/single/pkg/singleton.go @@ -0,0 +1,42 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import ( + "fmt" + "sync" +) + +var lock = &sync.Mutex{} + +type singleton struct { +} + +var instance *singleton + +//获取实例 +func GetInstance() *singleton { + if instance == nil { + lock.Lock() + defer lock.Unlock() + if instance == nil { + fmt.Println("创建单个实例") + instance = new (singleton) + } else { + fmt.Println("已创建单个实例!") + } + } else { + fmt.Println("已创建单个实例!") + } + + return instance +} \ No newline at end of file diff --git a/chapter3/adapter/actualCombat/client.go b/chapter3/adapter/actualCombat/client.go new file mode 100644 index 0000000..8dd7de8 --- /dev/null +++ b/chapter3/adapter/actualCombat/client.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//客户端 +type Client struct { +} + +//将Lightning类型接口插入电脑 +func (c *Client) InsertIntoComputer(com Computer) { + fmt.Println("客户端将Lightning类型接口插入计算机") + com.ConvertToUSB() +} diff --git a/chapter3/adapter/actualCombat/computer.go b/chapter3/adapter/actualCombat/computer.go new file mode 100644 index 0000000..11bf6bb --- /dev/null +++ b/chapter3/adapter/actualCombat/computer.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//电脑接口 +type Computer interface { + ConvertToUSB() +} diff --git a/chapter3/adapter/actualCombat/mac.go b/chapter3/adapter/actualCombat/mac.go new file mode 100644 index 0000000..efe32d5 --- /dev/null +++ b/chapter3/adapter/actualCombat/mac.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//Mac系统 +type Mac struct { +} + +//插入接口 +func (m *Mac) ConvertToUSB() { + fmt.Println("Lightning类型接口已插入Mac电脑") +} diff --git a/chapter3/adapter/actualCombat/windows.go b/chapter3/adapter/actualCombat/windows.go new file mode 100644 index 0000000..882bce4 --- /dev/null +++ b/chapter3/adapter/actualCombat/windows.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//Windows操作系统 +type Windows struct{} + +//插入USB接口到Windows电脑 +func (w *Windows) InsertIntoUSB() { + fmt.Println("USB接口已插入Windows电脑") +} diff --git a/chapter3/adapter/actualCombat/windowsAdapter.go b/chapter3/adapter/actualCombat/windowsAdapter.go new file mode 100644 index 0000000..9e8e797 --- /dev/null +++ b/chapter3/adapter/actualCombat/windowsAdapter.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//Windows系统适配器 +type Adapter struct { + WindowsMachine *Windows +} + +func (w *Adapter) ConvertToUSB() { + fmt.Println("适配器将Lightning类型信号转换为USB") + w.WindowsMachine.InsertIntoUSB() +} diff --git a/chapter3/adapter/example/adapter-object.go b/chapter3/adapter/example/adapter-object.go new file mode 100644 index 0000000..016f300 --- /dev/null +++ b/chapter3/adapter/example/adapter-object.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +//适配者类 +type ObjectAdaptee struct { +} + +// 目标接口 +type ObjectTarget interface { + Execute() +} + +//适配者类的方法 +func (b *ObjectAdaptee) SpecificExecute() { + fmt.Println("最终执行的方法") +} + +//适配器类 +type ObjectAdapter struct { + Adaptee ObjectAdaptee +} + +// 适配器类的方法 +func (p *ObjectAdapter) Execute() { + p.Adaptee.SpecificExecute() +} diff --git a/chapter3/adapter/example/adapter.go b/chapter3/adapter/example/adapter.go new file mode 100644 index 0000000..1f76346 --- /dev/null +++ b/chapter3/adapter/example/adapter.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +// 定义被适配的类 +type Adaptee struct { +} + +// 目标接口 +type Target interface { + Execute() +} + +//定义了用于执行的方法SpecificExecute() +func (a *Adaptee) SpecificExecute() { + fmt.Println("最终执行的方法") +} + +// Adapter 是新接口 Target 的适配器,继承了 Adaptee 类 +type Adapter struct { + *Adaptee +} + +// 实现 Target 接口,同时继承了 Adaptee 类 +func (a *Adapter) Execute() { + a.SpecificExecute() +} diff --git a/chapter3/adapter/main-actual-combat.go b/chapter3/adapter/main-actual-combat.go new file mode 100644 index 0000000..19a911f --- /dev/null +++ b/chapter3/adapter/main-actual-combat.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter3/adapter/actualCombat" + +func main() { + //创建客户端 + Client := &actualCombat.Client{} + Mac := &actualCombat.Mac{} + + //客户端插入Lightning类型连接器到Mac电脑 + Client.InsertIntoComputer(Mac) + + WindowsAdapter := &actualCombat.Windows{} + WindowsAdapterAdapter := &actualCombat.Adapter{ + WindowsMachine: WindowsAdapter, + } + + //客户端插入Lightning类型连接器到Windows适配器 + Client.InsertIntoComputer(WindowsAdapterAdapter) +} + +//$ go run main-actual-combat.go +//Lightning类型接口已插入Mac电脑 +//客户端将Lightning类型接口插入计算机 +//适配器将Lightning类型信号转换为USB +//USB接口已插入Windows电脑 diff --git a/chapter3/adapter/main.go b/chapter3/adapter/main.go new file mode 100644 index 0000000..e68b3e8 --- /dev/null +++ b/chapter3/adapter/main.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter3/adapter/pkg" +) + +func main() { + //创建客户端 + adapter := pkg.Adapter{} + adapter.Execute() +} + +//$ go run main.go +//最终执行的方法 diff --git a/chapter3/adapter/mainobj.go b/chapter3/adapter/mainobj.go new file mode 100644 index 0000000..7a0f78f --- /dev/null +++ b/chapter3/adapter/mainobj.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter3/adapter/pkg" +) + +func main() { + //创建客户端 + adapter := pkg.ObjectAdapter{} + adapter.Execute() +} + +//$ go run main.go +//最终执行的方法 diff --git a/chapter3/adapter/pkg/adapter-object.go b/chapter3/adapter/pkg/adapter-object.go new file mode 100644 index 0000000..4e2519f --- /dev/null +++ b/chapter3/adapter/pkg/adapter-object.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//定义需要被适配的类 +type ObjectAdaptee struct { +} + +// Target 是要适配的目标接口 +type ObjectTarget interface { + Execute() +} + +//定义了用于执行的方法SpecificExecute() +func (b *ObjectAdaptee) SpecificExecute() { + fmt.Println("最终执行的方法") +} + +//Adapter 是新接口 Target 的适配器,通过关联 Adaptee 类来实现 +type ObjectAdapter struct { + Adaptee ObjectAdaptee +} + +// 同时继承了 Adaptee 类 +func (p *ObjectAdapter) Execute() { + p.Adaptee.SpecificExecute() +} diff --git a/chapter3/adapter/pkg/adapter.go b/chapter3/adapter/pkg/adapter.go new file mode 100644 index 0000000..90d7c74 --- /dev/null +++ b/chapter3/adapter/pkg/adapter.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import ( + "fmt" +) + +// Adaptee 定义了需要被适配的类 +type Adaptee struct { +} + +// Target 是要适配的目标接口 +type Target interface { + Execute() +} + +//定义了用于执行的方法SpecificExecute() +func (a *Adaptee) SpecificExecute() { + fmt.Println("最终执行的方法") +} + +// Adapter 是新接口 Target 的适配器,继承了 Adaptee 类 +type Adapter struct { + *Adaptee +} + +// 实现 Target 接口,同时继承了 Adaptee 类 +func (a *Adapter) Execute() { + a.SpecificExecute() +} diff --git a/chapter3/bridge/actualCombat/canon.go b/chapter3/bridge/actualCombat/canon.go new file mode 100644 index 0000000..a98b36e --- /dev/null +++ b/chapter3/bridge/actualCombat/canon.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//佳能打印机 +type Canon struct { +} + +//打印文件 +func (p *Canon) PrintFile() { + fmt.Println("Printing by a Canon Printer") +} diff --git a/chapter3/bridge/actualCombat/computer.go b/chapter3/bridge/actualCombat/computer.go new file mode 100644 index 0000000..02220db --- /dev/null +++ b/chapter3/bridge/actualCombat/computer.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//电脑接口 +type Computer interface { + Print() + SetPrinter(Printer) +} diff --git a/chapter3/bridge/actualCombat/lenovo.go b/chapter3/bridge/actualCombat/lenovo.go new file mode 100644 index 0000000..ccb6f12 --- /dev/null +++ b/chapter3/bridge/actualCombat/lenovo.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//联想打印机 +type Lenovo struct { +} + +//打印文件 +func (p *Lenovo) PrintFile() { + fmt.Println("Printing by a Lenovo Printer") +} diff --git a/chapter3/bridge/actualCombat/mac.go b/chapter3/bridge/actualCombat/mac.go new file mode 100644 index 0000000..04ea52d --- /dev/null +++ b/chapter3/bridge/actualCombat/mac.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//Mac系统 +type Mac struct { + Printer Printer +} + +//打印 +func (m *Mac) Print() { + fmt.Println("Print request for Mac") + m.Printer.PrintFile() +} + +//设置打印机 +func (m *Mac) SetPrinter(p Printer) { + m.Printer = p +} diff --git a/chapter3/bridge/actualCombat/printer.go b/chapter3/bridge/actualCombat/printer.go new file mode 100644 index 0000000..7eb8cdd --- /dev/null +++ b/chapter3/bridge/actualCombat/printer.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//打印机接口 +type Printer interface { + PrintFile() +} diff --git a/chapter3/bridge/actualCombat/windows.go b/chapter3/bridge/actualCombat/windows.go new file mode 100644 index 0000000..f64bb9e --- /dev/null +++ b/chapter3/bridge/actualCombat/windows.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//Windows系统 +type Windows struct { + Printer Printer +} + +//打印 +func (w *Windows) Print() { + fmt.Println("Print request for Windows") + w.Printer.PrintFile() +} + +//设置打印机 +func (w *Windows) SetPrinter(p Printer) { + w.Printer = p +} diff --git a/chapter3/bridge/example/bridge.go b/chapter3/bridge/example/bridge.go new file mode 100644 index 0000000..bf549cc --- /dev/null +++ b/chapter3/bridge/example/bridge.go @@ -0,0 +1,51 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +//实现接口 +type Implementor interface { + Implementation(str string) +} + +//具体实现 +type ConcreteImplementor struct{} + +func (*ConcreteImplementor) Implementation(str string) { + fmt.Printf("打印信息:[%v]", str) +} + +//初始化具体实现对象 +func NewConcreteImplementor() *ConcreteImplementor { + return &ConcreteImplementor{} +} + +//抽象接口 +type Abstraction interface { + Execute(str string) +} + +//扩充抽象 +type RefinedAbstraction struct { + method Implementor +} + +//扩充抽象方法 +func (c *RefinedAbstraction) Execute(str string) { + c.method.Implementation(str) +} + +//初始化扩充抽象对象 +func NewRefinedAbstraction(im Implementor) *RefinedAbstraction { + return &RefinedAbstraction{method: im} +} diff --git a/chapter3/bridge/main-actual-combat.go b/chapter3/bridge/main-actual-combat.go new file mode 100644 index 0000000..999e284 --- /dev/null +++ b/chapter3/bridge/main-actual-combat.go @@ -0,0 +1,61 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter3/bridge/actualCombat" +) + +func main() { + //联想打印机 + lenovoPrinter := &actualCombat.Lenovo{} + //佳能打印机 + canonPrinter := &actualCombat.Canon{} + + //Mac打印 + macComputer := &actualCombat.Mac{} + + //Mac电脑用SetPrinter()方法设置联想打印机 + macComputer.SetPrinter(lenovoPrinter) + macComputer.Print() + fmt.Println() + + //Mac电脑用SetPrinter()方法设置佳能打印机 + macComputer.SetPrinter(canonPrinter) + macComputer.Print() + fmt.Println() + + winComputer := &actualCombat.Windows{} + //Windows电脑用SetPrinter()方法设置联想打印机 + winComputer.SetPrinter(lenovoPrinter) + winComputer.Print() + fmt.Println() + + ///Windows电脑用SetPrinter()方法设置佳能打印机 + winComputer.SetPrinter(canonPrinter) + winComputer.Print() + fmt.Println() +} + +//$ go run main-actual-combat.go +//Print request for Mac +//Printing by a Lenovo Printer +// +//Print request for Mac +//Printing by a Canon Printer +// +//Print request for Windows +//Printing by a Lenovo Printer +// +//Print request for Windows +//Printing by a Canon Printer diff --git a/chapter3/bridge/main.go b/chapter3/bridge/main.go new file mode 100644 index 0000000..2946f5f --- /dev/null +++ b/chapter3/bridge/main.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter3/bridge/example" + +func main() { + concreteImplementor := example.NewConcreteImplementor() + + refinedAbstraction := example. + NewRefinedAbstraction(concreteImplementor) + refinedAbstraction.Execute("Hello Bridge~") +} + +//$ go run main.go +//打印信息:[Hello Bridge~] diff --git a/chapter3/bridge/pkg/canon.go b/chapter3/bridge/pkg/canon.go new file mode 100644 index 0000000..5b7d15d --- /dev/null +++ b/chapter3/bridge/pkg/canon.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//佳能打印机 +type Canon struct { +} + +//打印文件 +func (p *Canon) PrintFile() { + fmt.Println("Printing by a Canon Printer") +} diff --git a/chapter3/bridge/pkg/computer.go b/chapter3/bridge/pkg/computer.go new file mode 100644 index 0000000..af64b49 --- /dev/null +++ b/chapter3/bridge/pkg/computer.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//电脑接口 +type Computer interface { + Print() + SetPrinter(Printer) +} diff --git a/chapter3/bridge/pkg/lenovo.go b/chapter3/bridge/pkg/lenovo.go new file mode 100644 index 0000000..e30fd29 --- /dev/null +++ b/chapter3/bridge/pkg/lenovo.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//联想打印机 +type Lenovo struct { +} + +//打印文件 +func (p *Lenovo) PrintFile() { + fmt.Println("Printing by a Lenovo Printer") +} diff --git a/chapter3/bridge/pkg/mac.go b/chapter3/bridge/pkg/mac.go new file mode 100644 index 0000000..0434a7c --- /dev/null +++ b/chapter3/bridge/pkg/mac.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//Mac系统 +type Mac struct { + Printer Printer +} + +//打印 +func (m *Mac) Print() { + fmt.Println("Print request for Mac") + m.Printer.PrintFile() +} + +//设置打印机 +func (m *Mac) SetPrinter(p Printer) { + m.Printer = p +} diff --git a/chapter3/bridge/pkg/printer.go b/chapter3/bridge/pkg/printer.go new file mode 100644 index 0000000..3365674 --- /dev/null +++ b/chapter3/bridge/pkg/printer.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//打印机接口 +type Printer interface { + PrintFile() +} diff --git a/chapter3/bridge/pkg/windows.go b/chapter3/bridge/pkg/windows.go new file mode 100644 index 0000000..949ce51 --- /dev/null +++ b/chapter3/bridge/pkg/windows.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//Windows系统 +type Windows struct { + Printer Printer +} + +//打印 +func (w *Windows) Print() { + fmt.Println("Print request for Windows") + w.Printer.PrintFile() +} + +//设置打印机 +func (w *Windows) SetPrinter(p Printer) { + w.Printer = p +} diff --git a/chapter3/composite/actualCombat/component.go b/chapter3/composite/actualCombat/component.go new file mode 100644 index 0000000..22437e7 --- /dev/null +++ b/chapter3/composite/actualCombat/component.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Component interface { + Search(string) +} diff --git a/chapter3/composite/actualCombat/file.go b/chapter3/composite/actualCombat/file.go new file mode 100644 index 0000000..368876d --- /dev/null +++ b/chapter3/composite/actualCombat/file.go @@ -0,0 +1,26 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type File struct { + Name string +} + +func (f *File) Search(keyword string) { + fmt.Printf("在文件 %s 中递归搜索关键 %s \n", f.Name, keyword) +} + +func (f *File) GetName() string { + return f.Name +} diff --git a/chapter3/composite/actualCombat/folder.go b/chapter3/composite/actualCombat/folder.go new file mode 100644 index 0000000..fbbf980 --- /dev/null +++ b/chapter3/composite/actualCombat/folder.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type Folder struct { + Components []Component + Name string +} + +func (f *Folder) Search(keyword string) { + fmt.Printf("在文件夹 %s 中递归搜索关键 %s \n", f.Name, keyword) + for _, composite := range f.Components { + composite.Search(keyword) + } +} + +func (f *Folder) Add(c Component) { + f.Components = append(f.Components, c) +} diff --git a/chapter3/composite/example/composite.go b/chapter3/composite/example/composite.go new file mode 100644 index 0000000..2b9af03 --- /dev/null +++ b/chapter3/composite/example/composite.go @@ -0,0 +1,56 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +// 组件接口 +type Component interface { + Execute() +} + +// 叶节点,用于描述层次结构中的原始叶节点对象 +type Leaf struct { + value int +} + +// 创建一个新的叶节点对象 +func NewLeaf(value int) *Leaf { + return &Leaf{value} +} + +// 打印叶节点对象的值 +func (l *Leaf) Execute() { + fmt.Printf("%v ", l.value) +} + +// 组件的组合 +type Composite struct { + children []Component +} + +// 创建一个新的组合对象 +func NewComposite() *Composite { + return &Composite{make([]Component, 0)} +} + +// 将一个新组件添加到组合中 +func (c *Composite) Add(component Component) { + c.children = append(c.children, component) +} + +// 遍历复合子对象 +func (c *Composite) Execute() { + for i := 0; i < len(c.children); i++ { + c.children[i].Execute() + } +} diff --git a/chapter3/composite/main-actual-combat.go b/chapter3/composite/main-actual-combat.go new file mode 100644 index 0000000..dc94ae9 --- /dev/null +++ b/chapter3/composite/main-actual-combat.go @@ -0,0 +1,44 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter3/composite/actualCombat" +) + +func main() { + File1 := &actualCombat.File{Name: "File1"} + File2 := &actualCombat.File{Name: "File2"} + File3 := &actualCombat.File{Name: "File3"} + + Folder1 := &actualCombat.Folder{ + Name: "Folder1", + } + + Folder1.Add(File1) + + Folder2 := &actualCombat.Folder{ + Name: "Folder2", + } + Folder2.Add(File2) + Folder2.Add(File3) + Folder2.Add(Folder1) + + Folder2.Search("keyword") +} + +//$ go run main-actual-combat.go +//在文件夹 Folder2 中递归搜索关键 keyword +//在文件 File2 中递归搜索关键 keyword +//在文件 File3 中递归搜索关键 keyword +//在文件夹 Folder1 中递归搜索关键 keyword +//在文件 File1 中递归搜索关键 keyword diff --git a/chapter3/composite/main.go b/chapter3/composite/main.go new file mode 100644 index 0000000..16c9b38 --- /dev/null +++ b/chapter3/composite/main.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter3/composite/example" + +func main() { + composite := example.NewComposite() + leaf1 := example.NewLeaf(99) + composite.Add(leaf1) + leaf2 := example.NewLeaf(100) + composite.Add(leaf2) + leaf3 := example.NewComposite() + composite.Add(leaf3) + composite.Execute() +} + +//$ go run main.go +//99 100 diff --git a/chapter3/composite/pkg/component.go b/chapter3/composite/pkg/component.go new file mode 100644 index 0000000..0e51a52 --- /dev/null +++ b/chapter3/composite/pkg/component.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type Component interface { + Search(string) +} diff --git a/chapter3/composite/pkg/file.go b/chapter3/composite/pkg/file.go new file mode 100644 index 0000000..21187a8 --- /dev/null +++ b/chapter3/composite/pkg/file.go @@ -0,0 +1,26 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +type File struct { + Name string +} + +func (f *File) Search(keyword string) { + fmt.Printf("在文件 %s 中递归搜索关键 %s \n", f.Name, keyword) +} + +func (f *File) GetName() string { + return f.Name +} \ No newline at end of file diff --git a/chapter3/composite/pkg/folder.go b/chapter3/composite/pkg/folder.go new file mode 100644 index 0000000..2a79c66 --- /dev/null +++ b/chapter3/composite/pkg/folder.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +type Folder struct { + Components []Component + Name string +} + +func (f *Folder) Search(keyword string) { + fmt.Printf("在文件夹 %s 中递归搜索关键 %s \n", f.Name, keyword) + for _, composite := range f.Components { + composite.Search(keyword) + } +} + +func (f *Folder) Add(c Component) { + f.Components = append(f.Components, c) +} diff --git a/chapter3/decorator/actualCombat/baseParts.go b/chapter3/decorator/actualCombat/baseParts.go new file mode 100644 index 0000000..70ba9c3 --- /dev/null +++ b/chapter3/decorator/actualCombat/baseParts.go @@ -0,0 +1,21 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//基础零件 +type BaseParts struct { +} + +//获取基础零件手机价格 +func (p *BaseParts) GetPrice() float32 { + return 2000 +} diff --git a/chapter3/decorator/actualCombat/decorator.go b/chapter3/decorator/actualCombat/decorator.go new file mode 100644 index 0000000..f74229e --- /dev/null +++ b/chapter3/decorator/actualCombat/decorator.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//装饰 +type Decorator struct { + Phone Phone +} + +//装饰设置组件方法 +func (d *Decorator) SetComponent(c Phone) { + d.Phone = c +} + +//装饰方法 +func (d *Decorator) GetPrice() { + if d.Phone != nil { + d.Phone.GetPrice() + } +} diff --git a/chapter3/decorator/actualCombat/iphone.go b/chapter3/decorator/actualCombat/iphone.go new file mode 100644 index 0000000..ea98e86 --- /dev/null +++ b/chapter3/decorator/actualCombat/iphone.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type IPhone struct { + Decorator +} + +//获取IPhone价格 +func (c *IPhone) GetPrice() float32 { + phonePrice := c.Phone.GetPrice() + return phonePrice + 6000 +} diff --git a/chapter3/decorator/actualCombat/phone.go b/chapter3/decorator/actualCombat/phone.go new file mode 100644 index 0000000..ea1a0fd --- /dev/null +++ b/chapter3/decorator/actualCombat/phone.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Phone interface { + GetPrice() float32 +} diff --git a/chapter3/decorator/actualCombat/xiaomi.go b/chapter3/decorator/actualCombat/xiaomi.go new file mode 100644 index 0000000..183e73b --- /dev/null +++ b/chapter3/decorator/actualCombat/xiaomi.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Xiaomi struct { + Decorator +} + +//小米手机的价格 +func (c *Xiaomi) GetPrice() float32 { + phonePrice := c.Phone.GetPrice() + return phonePrice + 1000 +} diff --git a/chapter3/decorator/example/decorator.go b/chapter3/decorator/example/decorator.go new file mode 100644 index 0000000..866463e --- /dev/null +++ b/chapter3/decorator/example/decorator.go @@ -0,0 +1,76 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +//组件接口 +type Component interface { + Operation() +} + +//具体组件 +type ConcreteComponent struct { +} + +//具体组件方法 +func (c *ConcreteComponent) Operation() { + fmt.Println("具体的对象开始操作...") +} + +//装饰 +type Decorator struct { + component Component +} + +//装饰设置组件方法 +func (d *Decorator) SetComponent(c Component) { + d.component = c +} + +//装饰方法 +func (d *Decorator) Operation() { + if d.component != nil { + d.component.Operation() + } +} + +//具体装饰器A +type DecoratorA struct { + Decorator +} + +//具体装饰器A的方法 +func (d *DecoratorA) Operation() { + d.component.Operation() + d.IndependentMethod() +} + +func (d *DecoratorA) IndependentMethod() { + fmt.Println("装饰A扩展的方法~") +} + +//具体装饰器B +type DecoratorB struct { + Decorator +} + +//具体装饰器B的方法 +func (d *DecoratorB) Operation() { + d.component.Operation() + fmt.Println(d.String()) +} + +//具体装饰器B的拓展方法 +func (d *DecoratorB) String() string { + return "装饰B扩展的方法~" +} diff --git a/chapter3/decorator/main-actual-combat.go b/chapter3/decorator/main-actual-combat.go new file mode 100644 index 0000000..4929421 --- /dev/null +++ b/chapter3/decorator/main-actual-combat.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter3/decorator/actualCombat" +) + +func main() { + //具体零件 + phone := &actualCombat.BaseParts{} + fmt.Printf("基础零件的价格为:%f\n", phone.GetPrice()) + + //定义添加IPhone手机 + iPhone := &actualCombat.IPhone{} + iPhone.SetComponent(phone) + fmt.Printf("苹果的价格为:%f\n", iPhone.GetPrice()) + + //定义添加Xiaomi手机 + xiaomi := &actualCombat.Xiaomi{} + xiaomi.SetComponent(phone) + fmt.Printf("小米的价格为:%f\n", xiaomi.GetPrice()) +} + +//$ go run main-actual-combat.go +//基础零件的价格为:2000.000000 +//苹果的价格为:8000.000000 +//小米的价格为:3000.000000 diff --git a/chapter3/decorator/main.go b/chapter3/decorator/main.go new file mode 100644 index 0000000..d08db09 --- /dev/null +++ b/chapter3/decorator/main.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter3/decorator/example" + +func main() { + concreteComponent := &example.ConcreteComponent{} + decoratorA := &example.DecoratorA{} + decoratorB := &example.DecoratorB{} + decoratorA.SetComponent(concreteComponent) + decoratorB.SetComponent(decoratorA) + decoratorB.Operation() +} + +//$ go run main.go +//具体的对象开始操作... +//装饰A扩展的方法~ +//装饰B扩展的方法~ diff --git a/chapter3/decorator/pkg/baseParts.go b/chapter3/decorator/pkg/baseParts.go new file mode 100644 index 0000000..4d37c40 --- /dev/null +++ b/chapter3/decorator/pkg/baseParts.go @@ -0,0 +1,21 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//基础零件 +type BaseParts struct { +} + +//获取基础零件手机价格 +func (p *BaseParts) GetPrice() float32 { + return 2000 +} diff --git a/chapter3/decorator/pkg/iphone.go b/chapter3/decorator/pkg/iphone.go new file mode 100644 index 0000000..f66d7e1 --- /dev/null +++ b/chapter3/decorator/pkg/iphone.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type IPhone struct { + Phone Phone +} + +//获取IPhone价格 +func (c *IPhone) GetPrice() float32 { + phonePrice := c.Phone.GetPrice() + return phonePrice + 6000 +} diff --git a/chapter3/decorator/pkg/phone.go b/chapter3/decorator/pkg/phone.go new file mode 100644 index 0000000..cd239fb --- /dev/null +++ b/chapter3/decorator/pkg/phone.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type Phone interface { + GetPrice() float32 +} \ No newline at end of file diff --git a/chapter3/decorator/pkg/xiaomi.go b/chapter3/decorator/pkg/xiaomi.go new file mode 100644 index 0000000..8ef5e45 --- /dev/null +++ b/chapter3/decorator/pkg/xiaomi.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +type Xiaomi struct { + Phone Phone +} + +//小米手机的价格 +func (c *Xiaomi) GetPrice() float32 { + phonePrice := c.Phone.GetPrice() + return phonePrice + 1000 +} diff --git a/chapter3/facade/actualCombat/account.go b/chapter3/facade/actualCombat/account.go new file mode 100644 index 0000000..8470205 --- /dev/null +++ b/chapter3/facade/actualCombat/account.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//账户 +type Account struct { + name string +} + +//创建账户 +func NewAccount(accountName string) *Account { + return &Account{ + name: accountName, + } +} + +//检查账户 +func (a *Account) CheckAccount(accountName string) error { + if a.name != accountName { + return fmt.Errorf("%s", "账户名不正确~") + } + fmt.Println("账户验证通过~") + return nil +} diff --git a/chapter3/facade/actualCombat/ledger.go b/chapter3/facade/actualCombat/ledger.go new file mode 100644 index 0000000..bd4d184 --- /dev/null +++ b/chapter3/facade/actualCombat/ledger.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//分类帐 +type Ledger struct { +} + +//生成分类帐条目 +func (s *Ledger) MakeEntry(accountID, txnType string, amount int) { + fmt.Printf("为账户:%s 生成分类帐条目,账目类型为:%s,金额为:%d\n", accountID, txnType, amount) + return +} diff --git a/chapter3/facade/actualCombat/notification.go b/chapter3/facade/actualCombat/notification.go new file mode 100644 index 0000000..d25e2f8 --- /dev/null +++ b/chapter3/facade/actualCombat/notification.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//通知 +type Notification struct { +} + +//发送信用通知 +func (n *Notification) SendWalletCreditNotification() { + fmt.Println("发送钱包信用通知...") +} + +//发送借款通知 +func (n *Notification) SendWalletDebitNotification() { + fmt.Println("发送钱包借款通知...") +} diff --git a/chapter3/facade/actualCombat/verificationCode.go b/chapter3/facade/actualCombat/verificationCode.go new file mode 100644 index 0000000..3baf4a5 --- /dev/null +++ b/chapter3/facade/actualCombat/verificationCode.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//验证码 +type VerificationCode struct { + code int +} + +//创建验证码 +func NewVerificationCode(code int) *VerificationCode { + return &VerificationCode{ + code: code, + } +} + +//检查验证码 +func (s *VerificationCode) CheckCode(incomingCode int) error { + if s.code != incomingCode { + return fmt.Errorf("%s", "验证码不正确") + } + fmt.Println("验证通过~") + return nil +} diff --git a/chapter3/facade/actualCombat/wallet.go b/chapter3/facade/actualCombat/wallet.go new file mode 100644 index 0000000..a523efb --- /dev/null +++ b/chapter3/facade/actualCombat/wallet.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//钱包 +type Wallet struct { + balance int +} + +//创建钱包 +func NewWallet() *Wallet { + return &Wallet{ + balance: 0, + } +} + +//添加金额 +func (w *Wallet) AddBalance(amount int) { + w.balance += amount + fmt.Println("添加钱包金额成功~") + return +} + +//借款金额 +func (w *Wallet) DebitBalance(amount int) error { + if w.balance < amount { + return fmt.Errorf("%s", "金额无效~") + } + fmt.Println("钱包金额足够~") + w.balance = w.balance - amount + return nil +} diff --git a/chapter3/facade/actualCombat/walletFacade.go b/chapter3/facade/actualCombat/walletFacade.go new file mode 100644 index 0000000..25642d7 --- /dev/null +++ b/chapter3/facade/actualCombat/walletFacade.go @@ -0,0 +1,81 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//定义钱包的外观类 +type WalletFacade struct { + Account *Account + Wallet *Wallet + VerificationCode *VerificationCode + Notification *Notification + Ledger *Ledger +} + +//创建钱包的外观类 +func NewWalletFacade(accountID string, code int) *WalletFacade { + WalletFacacde := &WalletFacade{ + Account: NewAccount(accountID), + VerificationCode: NewVerificationCode(code), + Wallet: NewWallet(), + Notification: &Notification{}, + Ledger: &Ledger{}, + } + return WalletFacacde +} + +//添加钱到钱包 +func (w *WalletFacade) AddMoneyToWallet(accountID string, securityCode int, amount int) error { + fmt.Println("添加钱到钱包") + //1.检查账户 + err := w.Account.CheckAccount(accountID) + if err != nil { + return err + } + //2.检查验证码 + err = w.VerificationCode.CheckCode(securityCode) + if err != nil { + return err + } + //3.添加金额 + w.Wallet.AddBalance(amount) + //4.发送信用通知 + w.Notification.SendWalletCreditNotification() + w.Ledger.MakeEntry(accountID, "credit", amount) + return nil +} + +//从钱包里扣款 +func (w *WalletFacade) DeductMoneyFromWallet(accountID string, securityCode int, amount int) error { + fmt.Println("从钱包里扣款") + //1.检查账户 + err := w.Account.CheckAccount(accountID) + if err != nil { + return err + } + + //2.检查验证码 + err = w.VerificationCode.CheckCode(securityCode) + if err != nil { + return err + } + //3.借款金额 + err = w.Wallet.DebitBalance(amount) + if err != nil { + return err + } + //4.发送借款通知 + w.Notification.SendWalletDebitNotification() + w.Ledger.MakeEntry(accountID, "credit", amount) + return nil +} diff --git a/chapter3/facade/example/facade.go b/chapter3/facade/example/facade.go new file mode 100644 index 0000000..ebc0c7f --- /dev/null +++ b/chapter3/facade/example/facade.go @@ -0,0 +1,80 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +//外观类 +type Facade struct { + subSystemA SubSystemA + subSystemB SubSystemB +} + +//初始化 +func NewFacade() *Facade { + return &Facade{ + subSystemA: SubSystemA{}, + subSystemB: SubSystemB{}, + } +} + +//外观方法A +func (c *Facade) MethodA() { + c.subSystemB.MethodThree() + c.subSystemA.MethodOne() + c.subSystemB.MethodFour() +} + +//外观方法B +func (c *Facade) MethodB() { + c.subSystemB.MethodFour() + c.subSystemA.MethodTwo() +} + +//子系统A +type SubSystemA struct { +} + +//初始化子系统B +func NewSubSystemA() *SubSystemA { + return &SubSystemA{} +} + +//子系统B方法 +func (c *SubSystemA) MethodOne() { + fmt.Println("SubSystemB - MethodOne") +} + +//子系统B方法 +func (c *SubSystemA) MethodTwo() { + fmt.Println("SubSystemB - MethodTwo") + +} + +//子系统B +type SubSystemB struct { +} + +//初始化子系统A +func NewSubSystemB() *SubSystemB { + return &SubSystemB{} +} + +//子系统A方法 +func (c *SubSystemB) MethodThree() { + fmt.Println("SubSystemA - MethodThree") +} + +//子系统A方法 +func (c *SubSystemB) MethodFour() { + fmt.Println("SubSystemA - MethodFour") +} diff --git a/chapter3/facade/main-actual-combat.go b/chapter3/facade/main-actual-combat.go new file mode 100644 index 0000000..e50d7cc --- /dev/null +++ b/chapter3/facade/main-actual-combat.go @@ -0,0 +1,54 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter3/facade/actualCombat" + "log" +) + +func main() { + fmt.Println() + //实例化外观模式 + WalletFacade := actualCombat.NewWalletFacade("barry", 1688) + fmt.Println() + + //添加16元到钱包 + err := WalletFacade.AddMoneyToWallet("barry", 1688, 16) + if err != nil { + log.Fatalf("Error: %s\n", err.Error()) + } + + fmt.Println() + //从钱包取出5元 + err = WalletFacade.DeductMoneyFromWallet("barry", 1688, 5) + if err != nil { + log.Fatalf("Error: %s\n", err.Error()) + } +} + +//$ go run main-actual-combat.go +// +//添加钱到钱包 +//账户验证通过~ +//验证通过~ +//添加钱包金额成功~ +//发送钱包信用通知... +//为账户:barry 生成分类帐条目,账目类型为:credit,金额为:16 +// +//从钱包里扣款 +//账户验证通过~ +//验证通过~ +//钱包金额足够~ +//发送钱包借款通知... +//为账户:barry 生成分类帐条目,账目类型为:credit,金额为:5 diff --git a/chapter3/facade/main.go b/chapter3/facade/main.go new file mode 100644 index 0000000..eaea562 --- /dev/null +++ b/chapter3/facade/main.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter3/facade/example" +) + +func main() { + fa := example.NewFacade() + fa.MethodA() + fa.MethodB() + + sub := example.NewSubSystemA() + sub.MethodOne() + sub.MethodTwo() +} + +//$ go run main.go +//SubSystemA - MethodThree +//SubSystemB - MethodOne +//SubSystemA - MethodFour +//SubSystemA - MethodFour +//SubSystemB - MethodTwo +//SubSystemB - MethodOne +//SubSystemB - MethodTwo diff --git a/chapter3/facade/pkg/account.go b/chapter3/facade/pkg/account.go new file mode 100644 index 0000000..45691b5 --- /dev/null +++ b/chapter3/facade/pkg/account.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//账户 +type Account struct { + name string +} + +//创建账户 +func NewAccount(accountName string) *Account { + return &Account{ + name: accountName, + } +} + +//检查账户 +func (a *Account) CheckAccount(accountName string) error { + if a.name != accountName { + return fmt.Errorf("%s","账户名不正确~") + } + fmt.Println("账户验证通过~") + return nil +} diff --git a/chapter3/facade/pkg/ledger.go b/chapter3/facade/pkg/ledger.go new file mode 100644 index 0000000..c7e7390 --- /dev/null +++ b/chapter3/facade/pkg/ledger.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//分类帐 +type Ledger struct { +} + +//生成分类帐条目 +func (s *Ledger) MakeEntry(accountID, txnType string, amount int) { + fmt.Printf("为账户:%s 生成分类帐条目,账目类型为:%s,金额为:%d\n", accountID, txnType, amount) + return +} diff --git a/chapter3/facade/pkg/notification.go b/chapter3/facade/pkg/notification.go new file mode 100644 index 0000000..f035c11 --- /dev/null +++ b/chapter3/facade/pkg/notification.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//通知 +type Notification struct { +} + +//发送信用通知 +func (n *Notification) SendWalletCreditNotification() { + fmt.Println("发送钱包信用通知...") +} + +//发送借款通知 +func (n *Notification) SendWalletDebitNotification() { + fmt.Println("发送钱包借款通知...") +} + diff --git a/chapter3/facade/pkg/verificationCode.go b/chapter3/facade/pkg/verificationCode.go new file mode 100644 index 0000000..15b32b5 --- /dev/null +++ b/chapter3/facade/pkg/verificationCode.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//验证码 +type VerificationCode struct { + code int +} + +//创建验证码 +func NewVerificationCode(code int) *VerificationCode { + return &VerificationCode{ + code: code, + } +} + +//检查验证码 +func (s *VerificationCode) CheckCode(incomingCode int) error { + if s.code != incomingCode { + return fmt.Errorf("%s","验证码不正确") + } + fmt.Println("验证通过~") + return nil +} diff --git a/chapter3/facade/pkg/wallet.go b/chapter3/facade/pkg/wallet.go new file mode 100644 index 0000000..5a50014 --- /dev/null +++ b/chapter3/facade/pkg/wallet.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//钱包 +type Wallet struct { + balance int +} + +//创建钱包 +func NewWallet() *Wallet { + return &Wallet{ + balance: 0, + } +} + +//添加金额 +func (w *Wallet) AddBalance(amount int) { + w.balance += amount + fmt.Println("添加钱包金额成功~") + return +} + +//借款金额 +func (w *Wallet) DebitBalance(amount int) error { + if w.balance < amount { + return fmt.Errorf("%s", "金额无效~") + } + fmt.Println("钱包金额足够~") + w.balance = w.balance - amount + return nil +} diff --git a/chapter3/facade/pkg/walletFacade.go b/chapter3/facade/pkg/walletFacade.go new file mode 100644 index 0000000..416dfd5 --- /dev/null +++ b/chapter3/facade/pkg/walletFacade.go @@ -0,0 +1,84 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +//定义钱包的外观模式 +type WalletFacade struct { + Account *Account + Wallet *Wallet + VerificationCode *VerificationCode + Notification *Notification + Ledger *Ledger +} + +//创建钱包的外观模式 +func NewWalletFacade(accountID string, code int) *WalletFacade { + fmt.Println("开始创建账户") + WalletFacacde := &WalletFacade{ + Account: NewAccount(accountID), + VerificationCode: NewVerificationCode(code), + Wallet: NewWallet(), + Notification: &Notification{}, + Ledger: &Ledger{}, + } + fmt.Println("账户已创建") + return WalletFacacde +} + +//添加钱到钱包 +func (w *WalletFacade) AddMoneyToWallet(accountID string, securityCode int, amount int) error { + fmt.Println("添加钱到钱包") + //1.检查账户 + err := w.Account.CheckAccount(accountID) + if err != nil { + return err + } + //2.检查验证码 + err = w.VerificationCode.CheckCode(securityCode) + if err != nil { + return err + } + //3.添加金额 + w.Wallet.AddBalance(amount) + //4.发送借款通知 + w.Notification.SendWalletCreditNotification() + //5. + w.Ledger.MakeEntry(accountID, "credit", amount) + return nil +} + +//从钱包里扣款 +func (w *WalletFacade) DeductMoneyFromWallet(accountID string, securityCode int, amount int) error { + fmt.Println("从钱包里扣款") + //1.检查账户 + err := w.Account.CheckAccount(accountID) + if err != nil { + return err + } + + //2.检查验证码 + err = w.VerificationCode.CheckCode(securityCode) + if err != nil { + return err + } + //3.借款金额 + err = w.Wallet.DebitBalance(amount) + if err != nil { + return err + } + //4.发送借款通知 + w.Notification.SendWalletDebitNotification() + w.Ledger.MakeEntry(accountID, "credit", amount) + return nil +} diff --git a/chapter3/flyweight/actualCombat/blueTeamDress.go b/chapter3/flyweight/actualCombat/blueTeamDress.go new file mode 100644 index 0000000..f4dfe2b --- /dev/null +++ b/chapter3/flyweight/actualCombat/blueTeamDress.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//蓝队服装 +type BlueTeamDress struct { + color string +} + +func (t *BlueTeamDress) GetColor() string { + return t.color +} + +func newBlueTeamDress() *BlueTeamDress { + return &BlueTeamDress{color: "blue"} +} diff --git a/chapter3/flyweight/actualCombat/dress.go b/chapter3/flyweight/actualCombat/dress.go new file mode 100644 index 0000000..ab56e2c --- /dev/null +++ b/chapter3/flyweight/actualCombat/dress.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//服装接口 +type Dress interface { + GetColor() string +} diff --git a/chapter3/flyweight/actualCombat/dressFactory.go b/chapter3/flyweight/actualCombat/dressFactory.go new file mode 100644 index 0000000..7944547 --- /dev/null +++ b/chapter3/flyweight/actualCombat/dressFactory.go @@ -0,0 +1,55 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +const ( + //蓝队服装类型 + BlueTeamDressType = "Blue Dress" + //红队服装类型 + RedTeamDressType = "Red Dress" +) + +var ( + DressFactorySingleInstance = &DressFactory{ + DressMap: make(map[string]Dress), + } +) + +//享元服装工厂 +type DressFactory struct { + DressMap map[string]Dress +} + +//获取服装类型 +func (d *DressFactory) GetDressByType(DressType string) (Dress, error) { + if d.DressMap[DressType] != nil { + return d.DressMap[DressType], nil + } + + if DressType == BlueTeamDressType { + d.DressMap[DressType] = newBlueTeamDress() + return d.DressMap[DressType], nil + } + if DressType == RedTeamDressType { + d.DressMap[DressType] = newRedTeamDress() + return d.DressMap[DressType], nil + } + + return nil, fmt.Errorf("%s", "Wrong Dress type") +} + +//获取服装工厂单例 +func GetDressFactorySingleInstance() *DressFactory { + return DressFactorySingleInstance +} diff --git a/chapter3/flyweight/actualCombat/game.go b/chapter3/flyweight/actualCombat/game.go new file mode 100644 index 0000000..811f27a --- /dev/null +++ b/chapter3/flyweight/actualCombat/game.go @@ -0,0 +1,26 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//创建游戏 +type NewGame struct { +} + +//创建蓝队队员 +func (ng *NewGame) AddBlueTeam(DressType string) *Player { + return NewPlayer("terrorist", DressType) +} + +//创建红队队员 +func (ng *NewGame) AddRedTeam(DressType string) *Player { + return NewPlayer("counterBlueTeam", DressType) +} diff --git a/chapter3/flyweight/actualCombat/player.go b/chapter3/flyweight/actualCombat/player.go new file mode 100644 index 0000000..1b21e4f --- /dev/null +++ b/chapter3/flyweight/actualCombat/player.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//队员类 +type Player struct { + Dress Dress + PlayerType string + lat int + long int +} + +//创建一个队员 +func NewPlayer(PlayerType, DressType string) *Player { + Dress, _ := GetDressFactorySingleInstance().GetDressByType(DressType) + return &Player{ + PlayerType: PlayerType, + Dress: Dress, + } +} + +//创建队员位置 +func (p *Player) NewLocation(lat, long int) { + p.lat = lat + p.long = long +} diff --git a/chapter3/flyweight/actualCombat/redTeamDress.go b/chapter3/flyweight/actualCombat/redTeamDress.go new file mode 100644 index 0000000..0927a9b --- /dev/null +++ b/chapter3/flyweight/actualCombat/redTeamDress.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//创建红队服装 +type RedTeamDress struct { + color string +} + +func (c *RedTeamDress) GetColor() string { + return c.color +} + +func newRedTeamDress() *RedTeamDress { + return &RedTeamDress{color: "red"} +} diff --git a/chapter3/flyweight/example/flyweight.go b/chapter3/flyweight/example/flyweight.go new file mode 100644 index 0000000..4d14e79 --- /dev/null +++ b/chapter3/flyweight/example/flyweight.go @@ -0,0 +1,63 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +//享元接口 +type Flyweight interface { + Operation() +} + +// 创建具体享元类,可以共享以支持大型有效的对象数量 +type ConcreteFlyweight struct { + intrinsicState string +} + +//具体享元对象初始化 +func (fw ConcreteFlyweight) Init(intrinsicState string) { + fw.intrinsicState = intrinsicState +} + +//具体享元对象的方法 +func (fw ConcreteFlyweight) Operation(extrinsicState string) string { + fmt.Println(fw.intrinsicState) + if extrinsicState != "" { + return extrinsicState + } + return "empty extrinsicState" +} + +// 创建一个新的具体享元类 +func NewConcreteFlyweight(state string) *ConcreteFlyweight { + return &ConcreteFlyweight{state} +} + +// 创建用于创建和存储享元的享元工厂类 +type FlyweightFactory struct { + pool map[string]*ConcreteFlyweight +} + +// 创建一个新的享元工厂对象 +func NewFlyweightFactory() *FlyweightFactory { + return &FlyweightFactory{pool: make(map[string]*ConcreteFlyweight)} +} + +// 获取或创建具体享元对象 +func (f *FlyweightFactory) GetFlyweight(state string) *ConcreteFlyweight { + flyweight, _ := f.pool[state] + if f.pool[state] == nil { + flyweight = NewConcreteFlyweight(state) + f.pool[state] = flyweight + } + return flyweight +} diff --git a/chapter3/flyweight/main-actual-combat.go b/chapter3/flyweight/main-actual-combat.go new file mode 100644 index 0000000..44419ae --- /dev/null +++ b/chapter3/flyweight/main-actual-combat.go @@ -0,0 +1,44 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter3/flyweight/actualCombat" +) + +func main() { + game := actualCombat.NewGame{} + + //创建红队 + game.AddBlueTeam(actualCombat.BlueTeamDressType) + game.AddBlueTeam(actualCombat.BlueTeamDressType) + game.AddBlueTeam(actualCombat.BlueTeamDressType) + game.AddBlueTeam(actualCombat.BlueTeamDressType) + + //创建蓝队 + game.AddRedTeam(actualCombat.RedTeamDressType) + game.AddRedTeam(actualCombat.RedTeamDressType) + game.AddRedTeam(actualCombat.RedTeamDressType) + + DressFactoryInstance := actualCombat.GetDressFactorySingleInstance() + + for DressType, Dress := range DressFactoryInstance.DressMap { + fmt.Printf("服装类型: %s\n服装颜色: %s\n", DressType, Dress.GetColor()) + } +} + +//$ go run main-actual-combat.go +//服装类型: Blue Dress +//服装颜色: blue +//服装类型: Red Dress +//服装颜色: red diff --git a/chapter3/flyweight/main.go b/chapter3/flyweight/main.go new file mode 100644 index 0000000..bff7fc9 --- /dev/null +++ b/chapter3/flyweight/main.go @@ -0,0 +1,32 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter3/flyweight/example" +) + +func main() { + factory := example.NewFlyweightFactory() + flyweight1 := factory.GetFlyweight("Barry") + flyweight2 := factory.GetFlyweight("Shirdon") + + fmt.Println(flyweight1.Operation("ok")) + fmt.Println(flyweight2.Operation("good")) +} + +//$ go run main.go +//Barry +//ok +//Shirdon +//good diff --git a/chapter3/flyweight/pkg/blueTeamDress.go b/chapter3/flyweight/pkg/blueTeamDress.go new file mode 100644 index 0000000..3057f12 --- /dev/null +++ b/chapter3/flyweight/pkg/blueTeamDress.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//蓝队服装 +type BlueTeamDress struct { + color string +} + +func (t *BlueTeamDress) GetColor() string { + return t.color +} + +func newBlueTeamDress() *BlueTeamDress { + return &BlueTeamDress{color: "blue"} +} diff --git a/chapter3/flyweight/pkg/dress.go b/chapter3/flyweight/pkg/dress.go new file mode 100644 index 0000000..cf139eb --- /dev/null +++ b/chapter3/flyweight/pkg/dress.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//服装接口 +type Dress interface { + GetColor() string +} \ No newline at end of file diff --git a/chapter3/flyweight/pkg/dressFactory.go b/chapter3/flyweight/pkg/dressFactory.go new file mode 100644 index 0000000..6ba597c --- /dev/null +++ b/chapter3/flyweight/pkg/dressFactory.go @@ -0,0 +1,55 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +import "fmt" + +const ( + //蓝队服装类型 + BlueTeamDressType = "Blue Dress" + //红队服装类型 + RedTeamDressType = "Red Dress" +) + +var ( + DressFactorySingleInstance = &DressFactory{ + DressMap: make(map[string]Dress), + } +) + +//享元服装工厂 +type DressFactory struct { + DressMap map[string]Dress +} + +//获取服装类型 +func (d *DressFactory) GetDressByType(DressType string) (Dress, error) { + if d.DressMap[DressType] != nil { + return d.DressMap[DressType], nil + } + + if DressType == BlueTeamDressType { + d.DressMap[DressType] = newBlueTeamDress() + return d.DressMap[DressType], nil + } + if DressType == RedTeamDressType { + d.DressMap[DressType] = newRedTeamDress() + return d.DressMap[DressType], nil + } + + return nil, fmt.Errorf("%s","Wrong Dress type") +} + +//获取服装工厂单例 +func GetDressFactorySingleInstance() *DressFactory { + return DressFactorySingleInstance +} diff --git a/chapter3/flyweight/pkg/game.go b/chapter3/flyweight/pkg/game.go new file mode 100644 index 0000000..f71ed09 --- /dev/null +++ b/chapter3/flyweight/pkg/game.go @@ -0,0 +1,26 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//创建游戏 +type NewGame struct { +} + +//创建蓝队队员 +func (ng *NewGame) AddBlueTeam(DressType string) *Player { + return NewPlayer("terrorist", DressType) +} + +//创建红队队员 +func (ng *NewGame) AddRedTeam(DressType string) *Player { + return NewPlayer("counterBlueTeam", DressType) +} diff --git a/chapter3/flyweight/pkg/player.go b/chapter3/flyweight/pkg/player.go new file mode 100644 index 0000000..e994765 --- /dev/null +++ b/chapter3/flyweight/pkg/player.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//队员类 +type Player struct { + Dress Dress + PlayerType string + lat int + long int +} + +//创建一个队员 +func NewPlayer(PlayerType, DressType string) *Player { + Dress, _ := GetDressFactorySingleInstance().GetDressByType(DressType) + return &Player{ + PlayerType: PlayerType, + Dress: Dress, + } +} + +//创建队员位置 +func (p *Player) NewLocation(lat, long int) { + p.lat = lat + p.long = long +} diff --git a/chapter3/flyweight/pkg/redTeamDress.go b/chapter3/flyweight/pkg/redTeamDress.go new file mode 100644 index 0000000..c1e97c2 --- /dev/null +++ b/chapter3/flyweight/pkg/redTeamDress.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//创建红队服装 +type RedTeamDress struct { + color string +} + +func (c *RedTeamDress) GetColor() string { + return c.color +} + +func newRedTeamDress() *RedTeamDress { + return &RedTeamDress{color: "red"} +} diff --git a/chapter3/proxy/actualCombat/apache.go b/chapter3/proxy/actualCombat/apache.go new file mode 100644 index 0000000..2a1543c --- /dev/null +++ b/chapter3/proxy/actualCombat/apache.go @@ -0,0 +1,49 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//Apache类 +type Apache struct { + Application *Application + maxAllowedRequest int + rateLimiter map[string]int +} + +//创建Apache服务器 +func NewApacheServer() *Apache { + return &Apache{ + Application: &Application{}, + maxAllowedRequest: 2, + rateLimiter: make(map[string]int), + } +} + +//处理请求 +func (n *Apache) HandleRequest(url, method string) (int, string) { + allowed := n.CheckRateLimiting(url) + if !allowed { + return 403, "Not Allowed" + } + return n.Application.HandleRequest(url, method) +} + +//检查频率限制 +func (n *Apache) CheckRateLimiting(url string) bool { + if n.rateLimiter[url] == 0 { + n.rateLimiter[url] = 1 + } + if n.rateLimiter[url] > n.maxAllowedRequest { + return false + } + n.rateLimiter[url] = n.rateLimiter[url] + 1 + return true +} diff --git a/chapter3/proxy/actualCombat/application.go b/chapter3/proxy/actualCombat/application.go new file mode 100644 index 0000000..b65510d --- /dev/null +++ b/chapter3/proxy/actualCombat/application.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//定义真实主体类 +type Application struct { +} + +//处理请求 +func (a *Application) HandleRequest(url, method string) (int, string) { + if url == "/user/status" && method == "GET" { + return 200, "Ok" + } + + if url == "/user/login" && method == "POST" { + return 201, "User Login" + } + return 404, "Not Ok" +} diff --git a/chapter3/proxy/actualCombat/server.go b/chapter3/proxy/actualCombat/server.go new file mode 100644 index 0000000..4bfe263 --- /dev/null +++ b/chapter3/proxy/actualCombat/server.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//定义主体服务器接口 +type Server interface { + HandleRequest(string, string) (int, string) +} diff --git a/chapter3/proxy/example/proxy.go b/chapter3/proxy/example/proxy.go new file mode 100644 index 0000000..3d831b2 --- /dev/null +++ b/chapter3/proxy/example/proxy.go @@ -0,0 +1,47 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +// 服务接口 +type ServiceInterface interface { + Execute(access string) +} + +// 服务实现了用于执行任务的 ServiceInterface 接口 +type Service struct { +} + +// 服务对象的方法 +func (t *Service) Execute(access string) { + fmt.Println("Proxy Service: " + access) +} + +// 代理对象 +type Proxy struct { + realService *Service +} + +// 创建代理对象 +func NewProxy() *Proxy { + return &Proxy{realService: &Service{}} +} + +// 拦截 Execute 命令并将其重新路由到服务命令 +func (t *Proxy) Execute(access string) { + if access == "yes" { + t.realService.Execute(access) + } +} diff --git a/chapter3/proxy/main-actual-combat.go b/chapter3/proxy/main-actual-combat.go new file mode 100644 index 0000000..a45e737 --- /dev/null +++ b/chapter3/proxy/main-actual-combat.go @@ -0,0 +1,58 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter3/proxy/actualCombat" +) + +func main() { + //初始化Apache服务器 + ApacheServer := actualCombat.NewApacheServer() + userStatusURL := "/user/status" + userLoginURL := "/user/login" + + //发送一个GET请求 + httpCode, body := ApacheServer.HandleRequest(userStatusURL, "GET") + fmt.Printf("\nUrl: %s\nHttpCode: %d\nBody: %s\n", userStatusURL, httpCode, body) + + //发送一个POST请求 + httpCode, body = ApacheServer.HandleRequest(userStatusURL, "POST") + fmt.Printf("\nUrl: %s\nHttpCode: %d\nBody: %s\n", userStatusURL, httpCode, body) + + //发送一个GET请求 + httpCode, body = ApacheServer.HandleRequest(userLoginURL, "POST") + fmt.Printf("\nUrl: %s\nHttpCode: %d\nBody: %s\n", userStatusURL, httpCode, body) + + //发送一个POST请求 + httpCode, body = ApacheServer.HandleRequest(userLoginURL, "GET") + fmt.Printf("\nUrl: %s\nHttpCode: %d\nBody: %s\n", userStatusURL, httpCode, body) +} + +//$ go run main-actual-combat.go +// +//Url: /user/status +//HttpCode: 200 +//Body: Ok +// +//Url: /user/status +//HttpCode: 404 +//Body: Not Ok +// +//Url: /user/status +//HttpCode: 201 +//Body: User Login +// +//Url: /user/status +//HttpCode: 404 +//Body: Not Ok diff --git a/chapter3/proxy/main.go b/chapter3/proxy/main.go new file mode 100644 index 0000000..6a76b86 --- /dev/null +++ b/chapter3/proxy/main.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter3/proxy/example" + +func main() { + proxy := example.NewProxy() + proxy.Execute("yes") +} + +//$ go run main.go +//Proxy Service: yes diff --git a/chapter3/proxy/pkg/apache.go b/chapter3/proxy/pkg/apache.go new file mode 100644 index 0000000..58bedb5 --- /dev/null +++ b/chapter3/proxy/pkg/apache.go @@ -0,0 +1,49 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//Apache类 +type Apache struct { + Application *Application + maxAllowedRequest int + rateLimiter map[string]int +} + +//创建Apache服务器 +func NewApacheServer() *Apache { + return &Apache{ + Application: &Application{}, + maxAllowedRequest: 2, + rateLimiter: make(map[string]int), + } +} + +//处理请求 +func (n *Apache) HandleRequest(url, method string) (int, string) { + allowed := n.CheckRateLimiting(url) + if !allowed { + return 403, "Not Allowed" + } + return n.Application.HandleRequest(url, method) +} + +//检查频率限制 +func (n *Apache) CheckRateLimiting(url string) bool { + if n.rateLimiter[url] == 0 { + n.rateLimiter[url] = 1 + } + if n.rateLimiter[url] > n.maxAllowedRequest { + return false + } + n.rateLimiter[url] = n.rateLimiter[url] + 1 + return true +} diff --git a/chapter3/proxy/pkg/application.go b/chapter3/proxy/pkg/application.go new file mode 100644 index 0000000..6c529e3 --- /dev/null +++ b/chapter3/proxy/pkg/application.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//定义真实主体类 +type Application struct { +} + +//处理请求 +func (a *Application) HandleRequest(url, method string) (int, string) { + if url == "/user/status" && method == "GET" { + return 200, "Ok" + } + + if url == "/user/login" && method == "POST" { + return 201, "User Login" + } + return 404, "Not Ok" +} diff --git a/chapter3/proxy/pkg/server.go b/chapter3/proxy/pkg/server.go new file mode 100644 index 0000000..7f1b03a --- /dev/null +++ b/chapter3/proxy/pkg/server.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package pkg + +//定义主体服务器接口 +type Server interface { + HandleRequest(string, string) (int, string) +} diff --git a/chapter4/chainOfResponsibility/actualCombat/cashier.go b/chapter4/chainOfResponsibility/actualCombat/cashier.go new file mode 100644 index 0000000..f08eb32 --- /dev/null +++ b/chapter4/chainOfResponsibility/actualCombat/cashier.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type Cashier struct { + next department +} + +func (c *Cashier) Execute(p *Patient) { + if p.PaymentDone { + fmt.Println("支付完成") + } + fmt.Println("收银员从病人那里收钱") +} + +func (c *Cashier) SetNext(next department) { + c.next = next +} diff --git a/chapter4/chainOfResponsibility/actualCombat/department.go b/chapter4/chainOfResponsibility/actualCombat/department.go new file mode 100644 index 0000000..2eecb7a --- /dev/null +++ b/chapter4/chainOfResponsibility/actualCombat/department.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type department interface { + Execute(*Patient) + SetNext(department) +} diff --git a/chapter4/chainOfResponsibility/actualCombat/doctor.go b/chapter4/chainOfResponsibility/actualCombat/doctor.go new file mode 100644 index 0000000..d1e58ab --- /dev/null +++ b/chapter4/chainOfResponsibility/actualCombat/doctor.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type Clinic struct { + next department +} + +func (d *Clinic) Execute(p *Patient) { + if p.ClinicCheckUpDone { + fmt.Println("医生已经检查过了") + d.next.Execute(p) + return + } + fmt.Println("医生正在检查病人") + p.ClinicCheckUpDone = true + d.next.Execute(p) +} + +func (d *Clinic) SetNext(next department) { + d.next = next +} diff --git a/chapter4/chainOfResponsibility/actualCombat/medical.go b/chapter4/chainOfResponsibility/actualCombat/medical.go new file mode 100644 index 0000000..cbd3447 --- /dev/null +++ b/chapter4/chainOfResponsibility/actualCombat/medical.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type Drugstore struct { + next department +} + +func (m *Drugstore) Execute(p *Patient) { + if p.MedicineDone { + fmt.Println("药品已经给病人") + m.next.Execute(p) + return + } + fmt.Println("正在给病人用药") + p.MedicineDone = true + m.next.Execute(p) +} + +func (m *Drugstore) SetNext(next department) { + m.next = next +} diff --git a/chapter4/chainOfResponsibility/actualCombat/patient.go b/chapter4/chainOfResponsibility/actualCombat/patient.go new file mode 100644 index 0000000..e353dc2 --- /dev/null +++ b/chapter4/chainOfResponsibility/actualCombat/patient.go @@ -0,0 +1,20 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Patient struct { + Name string + RegistrationDone bool + ClinicCheckUpDone bool + MedicineDone bool + PaymentDone bool +} diff --git a/chapter4/chainOfResponsibility/actualCombat/reception.go b/chapter4/chainOfResponsibility/actualCombat/reception.go new file mode 100644 index 0000000..9e2e92b --- /dev/null +++ b/chapter4/chainOfResponsibility/actualCombat/reception.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type Reception struct { + next department +} + +func (r *Reception) Execute(p *Patient) { + if p.RegistrationDone { + fmt.Println("已完成患者登记") + r.next.Execute(p) + return + } + fmt.Println("正在接待登记病人") + p.RegistrationDone = true + r.next.Execute(p) +} + +func (r *Reception) SetNext(next department) { + r.next = next +} diff --git a/chapter4/chainOfResponsibility/example/chainOfResponsibility.go b/chapter4/chainOfResponsibility/example/chainOfResponsibility.go new file mode 100644 index 0000000..27fad7c --- /dev/null +++ b/chapter4/chainOfResponsibility/example/chainOfResponsibility.go @@ -0,0 +1,62 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +// Handler 定义了一个处理程序来处理给定的 handleID +type Handler interface { + SetNext(handler Handler) + Handle(handleID int) int +} + +//基础处理者 +type BaseHandler struct { + name string + next Handler + handleID int +} + +//NewHandler 返回一个新的处理程序 +func NewBaseHandler(name string, next Handler, handleID int) Handler { + return &BaseHandler{name, next, handleID} +} + +// Handle 处理给定的 handleID +func (h *BaseHandler) Handle(handleID int) int { + if handleID < 4 { + ch := &ConcreteHandler{} + ch.Handle(handleID) + fmt.Println(h.name) + + if h.next != nil { + h.next.Handle(handleID + 1) + } + + return handleID + 1 + } + return 0 +} + +// 设置下一个处理者 +func (h *BaseHandler) SetNext(handler Handler) { + h.next = handler +} + +//具体处理者 +type ConcreteHandler struct { +} + +//具体处理者的处理方法 +func (ch *ConcreteHandler) Handle(handleID int) { + fmt.Println("ConcreteHandler handleID:", handleID) +} diff --git a/chapter4/chainOfResponsibility/main-actual-combat.go b/chapter4/chainOfResponsibility/main-actual-combat.go new file mode 100644 index 0000000..5aa99fc --- /dev/null +++ b/chapter4/chainOfResponsibility/main-actual-combat.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/chainOfResponsibility/actualCombat" +) + +func main() { + + cashier := &actualCombat.Cashier{} + + //设置下一个医务部门 + medical := &actualCombat.Drugstore{} + medical.SetNext(cashier) + + //设置下一个医务部门 + doctor := &actualCombat.Clinic{} + doctor.SetNext(medical) + + //设置下一个医务部门 + reception := &actualCombat.Reception{} + reception.SetNext(doctor) + + patient := &actualCombat.Patient{Name: "Jack"} + //设置病人 + reception.Execute(patient) +} + +//$ go run main-actual-combat.go +//正在接待登记病人 +//医生正在检查病人 +//正在给病人用药 +//收银员从病人那里收钱 diff --git a/chapter4/chainOfResponsibility/main.go b/chapter4/chainOfResponsibility/main.go new file mode 100644 index 0000000..256df3e --- /dev/null +++ b/chapter4/chainOfResponsibility/main.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter4/chainOfResponsibility/example" +) + +func main() { + barry := example.NewBaseHandler("Barry", nil, 1) + shirdon := example.NewBaseHandler("Shirdon", barry, 2) + jack := example.NewBaseHandler("Shirdon", shirdon, 3) + res := shirdon.Handle(2) + res1 := jack.Handle(3) + fmt.Println(res) + fmt.Println(res1) +} + +//$ go run main.go +//ConcreteHandler handleID: 2 +//Shirdon +//ConcreteHandler handleID: 3 +//Barry +//ConcreteHandler handleID: 3 +//Shirdon +//3 +//4 diff --git a/chapter4/command/actualCombat/button.go b/chapter4/command/actualCombat/button.go new file mode 100644 index 0000000..d321602 --- /dev/null +++ b/chapter4/command/actualCombat/button.go @@ -0,0 +1,20 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Button struct { + Command Command +} + +func (b *Button) Press() { + b.Command.Execute() +} diff --git a/chapter4/command/actualCombat/command.go b/chapter4/command/actualCombat/command.go new file mode 100644 index 0000000..f247970 --- /dev/null +++ b/chapter4/command/actualCombat/command.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Command interface { + Execute() +} diff --git a/chapter4/command/actualCombat/device.go b/chapter4/command/actualCombat/device.go new file mode 100644 index 0000000..cec52dc --- /dev/null +++ b/chapter4/command/actualCombat/device.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Device interface { + On() + Off() +} diff --git a/chapter4/command/actualCombat/light.go b/chapter4/command/actualCombat/light.go new file mode 100644 index 0000000..837a40f --- /dev/null +++ b/chapter4/command/actualCombat/light.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type Light struct { + isRunning bool +} + +func (t *Light) On() { + t.isRunning = true + fmt.Println("打开灯...") +} + +func (t *Light) Off() { + t.isRunning = false + fmt.Println("关闭灯...") +} diff --git a/chapter4/command/actualCombat/offCommand.go b/chapter4/command/actualCombat/offCommand.go new file mode 100644 index 0000000..b1eddcf --- /dev/null +++ b/chapter4/command/actualCombat/offCommand.go @@ -0,0 +1,20 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type OffCommand struct { + Device Device +} + +func (c *OffCommand) Execute() { + c.Device.Off() +} diff --git a/chapter4/command/actualCombat/onCommand.go b/chapter4/command/actualCombat/onCommand.go new file mode 100644 index 0000000..04f5178 --- /dev/null +++ b/chapter4/command/actualCombat/onCommand.go @@ -0,0 +1,20 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type OnCommand struct { + Device Device +} + +func (c *OnCommand) Execute() { + c.Device.On() +} diff --git a/chapter4/command/example/command.go b/chapter4/command/example/command.go new file mode 100644 index 0000000..59266fd --- /dev/null +++ b/chapter4/command/example/command.go @@ -0,0 +1,99 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +type Command interface { + Execute() +} + +// 调用者类 +type Invoker struct { + cmds []Command +} + +// SetCommand 方法用于设置命令 +func (c *Invoker) SetCommand(cmd Command) { + c.cmds = append(c.cmds, cmd) +} + +// ExecuteCommand 方法用于执行命令 +func (c *Invoker) ExecuteCommand() { + for _, cmd := range c.cmds { + cmd.Execute() + } +} + +// 初始化调用者对象 +func NewInvoker() *Invoker { + return &Invoker{} +} + +// 接收者类 +type Receiver struct { +} + +// 初始化接收者对象 +func NewReceiver() *Receiver { + return &Receiver{} +} + +//接收者具体执行操作1 +func (f *Receiver) operation1(a string) { + fmt.Println("operation1:", a) +} + +//接收者具体执行操作2 +func (f *Receiver) operation2(a, b, c string) { + fmt.Println("operation2:", a, b, c) +} + +// 具体命令1 +type Command1 struct { + name string + receiver *Receiver +} + +// 初始化Command1对象 +func NewCommand1(name string, receiverObj *Receiver) *Command1 { + return &Command1{ + name: name, + receiver: receiverObj, + } +} + +//具体命令1执行操作 +func (c *Command1) Execute() { + c.receiver.operation1(c.name) +} + +// 具体命令2 +type Command2 struct { + name string + receiver *Receiver +} + +// 初始化Command2对象 +func NewCommand2(name string, receiverObj *Receiver) *Command2 { + return &Command2{ + name: name, + receiver: receiverObj, + } +} + +//具体命令2执行操作 +func (c *Command2) Execute() { + c.receiver.operation2(c.name, c.name, c.name) +} diff --git a/chapter4/command/main-actual-combat.go b/chapter4/command/main-actual-combat.go new file mode 100644 index 0000000..3a6c1da --- /dev/null +++ b/chapter4/command/main-actual-combat.go @@ -0,0 +1,49 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/command/actualCombat" +) + +func main() { + //初始化具体接收者对象 + Light := &actualCombat.Light{} + + //发送打开命令 + onCommand := &actualCombat.OnCommand{ + Device: Light, + } + + //发送关闭命令 + offCommand := &actualCombat.OffCommand{ + Device: Light, + } + + //接收打开命令 + onButton := &actualCombat.Button{ + Command: onCommand, + } + //按打开命令键 + onButton.Press() + + //接收关闭命令 + offButton := &actualCombat.Button{ + Command: offCommand, + } + //按关闭命令键 + offButton.Press() +} + +//$ go run main-actual-combat.go +//打开灯... +//关闭灯... diff --git a/chapter4/command/main.go b/chapter4/command/main.go new file mode 100644 index 0000000..f852c66 --- /dev/null +++ b/chapter4/command/main.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter4/command/example" + +func main() { + //创建接收者 + receiver := example.NewReceiver() + cc := example.NewInvoker() + //创建具体命令对象,如有需要可将其关联至接收者 + cmd1 := example.NewCommand1("commandA", receiver) + cmd2 := example.NewCommand2("commandB", receiver) + cc.SetCommand(cmd1) + cc.SetCommand(cmd2) + //执行命令 + cc.ExecuteCommand() +} + +//operation1: commandA +//operation2: commandB commandB commandB diff --git a/chapter4/iterator/actualCombat/collection.go b/chapter4/iterator/actualCombat/collection.go new file mode 100644 index 0000000..4534b73 --- /dev/null +++ b/chapter4/iterator/actualCombat/collection.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Collection interface { + CreateIterator() Iterator +} diff --git a/chapter4/iterator/actualCombat/iterator.go b/chapter4/iterator/actualCombat/iterator.go new file mode 100644 index 0000000..7cd91b3 --- /dev/null +++ b/chapter4/iterator/actualCombat/iterator.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Iterator interface { + HasNext() bool + GetNext() *User +} diff --git a/chapter4/iterator/actualCombat/user.go b/chapter4/iterator/actualCombat/user.go new file mode 100644 index 0000000..877bb33 --- /dev/null +++ b/chapter4/iterator/actualCombat/user.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type User struct { + Name string + Age int +} diff --git a/chapter4/iterator/actualCombat/userCollection.go b/chapter4/iterator/actualCombat/userCollection.go new file mode 100644 index 0000000..f1e243d --- /dev/null +++ b/chapter4/iterator/actualCombat/userCollection.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type UserCollection struct { + Users []*User +} + +func (u *UserCollection) CreateIterator() Iterator { + return &UserIterator{ + Users: u.Users, + } +} diff --git a/chapter4/iterator/actualCombat/userIterator.go b/chapter4/iterator/actualCombat/userIterator.go new file mode 100644 index 0000000..fa9b186 --- /dev/null +++ b/chapter4/iterator/actualCombat/userIterator.go @@ -0,0 +1,33 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type UserIterator struct { + Index int + Users []*User +} + +func (u *UserIterator) HasNext() bool { + if u.Index < len(u.Users) { + return true + } + return false + +} +func (u *UserIterator) GetNext() *User { + if u.HasNext() { + user := u.Users[u.Index] + u.Index++ + return user + } + return nil +} diff --git a/chapter4/iterator/example/iterator.go b/chapter4/iterator/example/iterator.go new file mode 100644 index 0000000..ba8b525 --- /dev/null +++ b/chapter4/iterator/example/iterator.go @@ -0,0 +1,64 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" + "time" +) + +// 迭代器接口 +type Iterator interface { + // 返回是否存在另一个下一个元素 + HasMore() bool + + // 递增迭代器,用于指向下一个元素 + GetNext() +} + +//集合接口 +type Collection interface { + CreateIterator() Iterator +} + +//具体集合 +type ConcreteCollection struct { +} + +//初始化具体集合对象,用于创建具体迭代器对象 +func (u *ConcreteCollection) CreateIterator() Iterator { + return &ConcreteIterator{ + IterationState: true, + } +} + +// 具体迭代器 +type ConcreteIterator struct { + IterationState bool +} + +//具体迭代器的方法 +func (i *ConcreteIterator) HasMore() bool { + if i.IterationState == true { + return true + } else { + return false + } +} + +//具体迭代器的方法,用于递增迭代器以指向下一个元素 +func (i *ConcreteIterator) GetNext() { + if i.HasMore() { + time.Sleep(1 * time.Second) + fmt.Println("GetNext") + } +} diff --git a/chapter4/iterator/main-actual-combat.go b/chapter4/iterator/main-actual-combat.go new file mode 100644 index 0000000..23c1fe7 --- /dev/null +++ b/chapter4/iterator/main-actual-combat.go @@ -0,0 +1,49 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter4/iterator/actualCombat" +) + +func main() { + + //声明用户对象User1 + user1 := &actualCombat.User{ + Name: "Jack", + Age: 30, + } + //声明用户对象User2 + user2 := &actualCombat.User{ + Name: "Barry", + Age: 20, + } + + //声明具体集合对象 + userCollection := &actualCombat.UserCollection{ + Users: []*actualCombat.User{user1, user2}, + } + + //声明具体迭代器对象 + iterator := userCollection.CreateIterator() + + //执行具体方法 + for iterator.HasNext() { + user := iterator.GetNext() + fmt.Printf("User is %+v\n", user) + } +} + +//$ go run main-actual-combat.go +//User is &{Name:Jack Age:30} +//User is &{Name:Barry Age:20} diff --git a/chapter4/iterator/main.go b/chapter4/iterator/main.go new file mode 100644 index 0000000..61f1d2e --- /dev/null +++ b/chapter4/iterator/main.go @@ -0,0 +1,30 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/iterator/example" +) + +func main() { + + //声明具体集合对象 + concreteCollection := &example.ConcreteCollection{} + + //声明具体迭代器对象 + iterator := concreteCollection.CreateIterator() + + //执行具体方法 + for iterator.HasMore() { + iterator.GetNext() + } +} diff --git a/chapter4/mediator/actualCombat/freightTrain.go b/chapter4/mediator/actualCombat/freightTrain.go new file mode 100644 index 0000000..9841da5 --- /dev/null +++ b/chapter4/mediator/actualCombat/freightTrain.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//货运列车类 +type FreightTrain struct { + Mediator Mediator +} + +//火车到达 +func (g *FreightTrain) Arrive() { + if !g.Mediator.CanArrive(g) { + fmt.Println("FreightTrain: Arrival blocked, waiting") + return + } + fmt.Println("FreightTrain: Arrived") +} + +//火车离开 +func (g *FreightTrain) Depart() { + fmt.Println("FreightTrain: Leaving") + g.Mediator.NotifyAboutDeparture() +} + +//允许到达 +func (g *FreightTrain) PermitArrival() { + fmt.Println("FreightTrain: Arrival permitted") + g.Arrive() +} diff --git a/chapter4/mediator/actualCombat/mediator.go b/chapter4/mediator/actualCombat/mediator.go new file mode 100644 index 0000000..66ae171 --- /dev/null +++ b/chapter4/mediator/actualCombat/mediator.go @@ -0,0 +1,17 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Mediator interface { + CanArrive(Train) bool + NotifyAboutDeparture() +} diff --git a/chapter4/mediator/actualCombat/passengerTrain.go b/chapter4/mediator/actualCombat/passengerTrain.go new file mode 100644 index 0000000..8222cfc --- /dev/null +++ b/chapter4/mediator/actualCombat/passengerTrain.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//客运火车类 +type PassengerTrain struct { + Mediator Mediator +} + +//火车到达 +func (p *PassengerTrain) Arrive() { + if !p.Mediator.CanArrive(p) { + fmt.Println("PassengerTrain: Arrival blocked, waiting") + return + } + fmt.Println("PassengerTrain: Arrived") +} + +//火车离开 +func (p *PassengerTrain) Depart() { + fmt.Println("PassengerTrain: Leaving") + p.Mediator.NotifyAboutDeparture() +} + +//允许到达 +func (p *PassengerTrain) PermitArrival() { + fmt.Println("PassengerTrain: Arrival permitted, arriving") + p.Arrive() +} diff --git a/chapter4/mediator/actualCombat/stationManager.go b/chapter4/mediator/actualCombat/stationManager.go new file mode 100644 index 0000000..be7e3df --- /dev/null +++ b/chapter4/mediator/actualCombat/stationManager.go @@ -0,0 +1,43 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type StationManager struct { + isPlatformFree bool + trainQueue []Train +} + +func NewStationManger() *StationManager { + return &StationManager{ + isPlatformFree: true, + } +} + +func (s *StationManager) CanArrive(t Train) bool { + if s.isPlatformFree { + s.isPlatformFree = false + return true + } + s.trainQueue = append(s.trainQueue, t) + return false +} + +func (s *StationManager) NotifyAboutDeparture() { + if !s.isPlatformFree { + s.isPlatformFree = true + } + if len(s.trainQueue) > 0 { + firstTrainInQueue := s.trainQueue[0] + s.trainQueue = s.trainQueue[1:] + firstTrainInQueue.PermitArrival() + } +} diff --git a/chapter4/mediator/actualCombat/train.go b/chapter4/mediator/actualCombat/train.go new file mode 100644 index 0000000..157af71 --- /dev/null +++ b/chapter4/mediator/actualCombat/train.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Train interface { + Arrive() + Depart() + PermitArrival() +} diff --git a/chapter4/mediator/example/mediator.go b/chapter4/mediator/example/mediator.go new file mode 100644 index 0000000..e0e38ca --- /dev/null +++ b/chapter4/mediator/example/mediator.go @@ -0,0 +1,87 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +// 同事类接口 +type Colleague interface { + SetMediator(mediator Mediator) +} + +// 具体同事1 +type ConcreteColleague1 struct { + mediator Mediator +} + +// 设置中介 +func (b *ConcreteColleague1) SetMediator(mediator Mediator) { + b.mediator = mediator +} + +// 执行动作 +func (b *ConcreteColleague1) Respond() { + fmt.Println("具体同事1:ConcreteColleague1回复中...") + b.mediator.Communicate("ConcreteColleague1") + return +} + +// 具体同事2 +type ConcreteColleague2 struct { + mediator Mediator +} + +// 设置中介 +func (t *ConcreteColleague2) SetMediator(mediator Mediator) { + t.mediator = mediator +} + +// 通过中介者谈话 +func (t *ConcreteColleague2) Talk() { + fmt.Println("通过中介者谈话") + t.mediator.Communicate("ConcreteColleague2") +} + +// 执行动作 +func (t *ConcreteColleague2) Respond() { + fmt.Println("具体同事2:ConcreteColleague2回复中...") +} + +// Mediator 描述了具体同事之间通信的接口 +type Mediator interface { + Communicate(who string) +} + +// ConcreateMediator 描述了 ConcreteColleague1 和 ConcreteColleague2 之间的中介 +type ConcreteMediator struct { + ConcreteColleague1 + ConcreteColleague2 +} + +// NewMediator 创建一个具体中介者 ConcreateMediator +func NewMediator() *ConcreteMediator { + mediator := &ConcreteMediator{} + mediator.ConcreteColleague1.SetMediator(mediator) + mediator.ConcreteColleague2.SetMediator(mediator) + return mediator +} + +// Communicate 在 ConcreteColleague1 和 ConcreteColleague2 之间进行通信 +func (m *ConcreteMediator) Communicate(who string) { + if who == "ConcreteColleague2" { + m.ConcreteColleague1.Respond() + return + } else if who == "ConcreteColleague1" { + m.ConcreteColleague2.Respond() + return + } +} diff --git a/chapter4/mediator/main-actual-combat.go b/chapter4/mediator/main-actual-combat.go new file mode 100644 index 0000000..3d05b30 --- /dev/null +++ b/chapter4/mediator/main-actual-combat.go @@ -0,0 +1,41 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/mediator/actualCombat" +) + +func main() { + //声明具体中介者 + stationManager := actualCombat.NewStationManger() + + //声明客运火车 + passengerTrain := &actualCombat.PassengerTrain{ + Mediator: stationManager, + } + //声明货运火车 + freightTrain := &actualCombat.FreightTrain{ + Mediator: stationManager, + } + + passengerTrain.Arrive() + freightTrain.Arrive() + passengerTrain.Depart() +} + +//$ go run main-actual-combat.go +//PassengerTrain: Arrived +//FreightTrain: Arrival blocked, waiting +//PassengerTrain: Leaving +//FreightTrain: Arrival permitted +//FreightTrain: Arrived diff --git a/chapter4/mediator/main.go b/chapter4/mediator/main.go new file mode 100644 index 0000000..96e167a --- /dev/null +++ b/chapter4/mediator/main.go @@ -0,0 +1,24 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter4/mediator/example" + +func main() { + mediator := example.NewMediator() + mediator.ConcreteColleague2.Talk() +} + +//$ go run main.go +//通过中介者谈话 +//具体同事1:ConcreteColleague1回复中... +//具体同事2:ConcreteColleague2回复中... diff --git a/chapter4/memento/actualCombat/caretaker.go b/chapter4/memento/actualCombat/caretaker.go new file mode 100644 index 0000000..eaced38 --- /dev/null +++ b/chapter4/memento/actualCombat/caretaker.go @@ -0,0 +1,27 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//负责人类 +type Caretaker struct { + MementoArray []*Memento +} + +//添加备忘录 +func (c *Caretaker) AddMemento(m *Memento) { + c.MementoArray = append(c.MementoArray, m) +} + +//获取备忘录 +func (c *Caretaker) GetMemento(index int) *Memento { + return c.MementoArray[index] +} diff --git a/chapter4/memento/actualCombat/memento.go b/chapter4/memento/actualCombat/memento.go new file mode 100644 index 0000000..59b7345 --- /dev/null +++ b/chapter4/memento/actualCombat/memento.go @@ -0,0 +1,22 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//备忘录类状态 +type Memento struct { + State string +} + +//获取设置好的状态 +func (m *Memento) GetSavedState() string { + return m.State +} diff --git a/chapter4/memento/actualCombat/originator.go b/chapter4/memento/actualCombat/originator.go new file mode 100644 index 0000000..a30720d --- /dev/null +++ b/chapter4/memento/actualCombat/originator.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//原发器类 +type Originator struct { + State string +} + +//创建备忘录 +func (e *Originator) CreateMemento() *Memento { + return &Memento{State: e.State} +} + +//恢复原发器对象的状态 +func (e *Originator) RestoreMemento(m *Memento) { + e.State = m.GetSavedState() +} + +//设置状态 +func (e *Originator) SetState(State string) { + e.State = State +} + +//获取状态 +func (e *Originator) GetState() string { + return e.State +} diff --git a/chapter4/memento/example/memento.go b/chapter4/memento/example/memento.go new file mode 100644 index 0000000..35bc2fe --- /dev/null +++ b/chapter4/memento/example/memento.go @@ -0,0 +1,78 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +//备忘录 Memento 存储原发器 Originator 的状态 +type Memento struct { + state int +} + +// 将数字的值乘以10倍 +func (m *Memento) getState() int { + return m.state +} + +// 创建一个新的备忘录*Memento +func NewMemento(value int) *Memento { + return &Memento{value} +} + +// Originator 代表一个可以被操作的整数 +type Originator struct { + value int +} + +// NewOriginator 创建一个新的原发器 Originator +func NewOriginator(value int) *Originator { + return &Originator{value} +} + +// 将数字的值乘以10倍 +func (n *Originator) TenTimes() { + n.value = 10 * n.value +} + +// 获取数字值的一半 +func (n *Originator) HalfTimes() { + n.value /= 2 +} + +// 返回数字的值 +func (n *Originator) Value() int { + return n.value +} + +// 使用原发器创建一个备忘录 Memento +func (n *Originator) CreateMemento() *Memento { + return NewMemento(n.value) +} + +// 将原发器 Originator 的值恢复为指定版本的备忘录的值 +func (n *Originator) RestoreMemento(memento *Memento) { + n.value = memento.getState() +} + +//负责人类 +type Caretaker struct { + Originator Originator + History []*Memento +} + +//添加备忘录 +func (c *Caretaker) AddMemento(m *Memento) { + c.History = append(c.History, m) +} + +//获取备忘录 +func (c *Caretaker) GetMemento(index int) *Memento { + return c.History[index] +} diff --git a/chapter4/memento/main-actual-combat.go b/chapter4/memento/main-actual-combat.go new file mode 100644 index 0000000..7b50313 --- /dev/null +++ b/chapter4/memento/main-actual-combat.go @@ -0,0 +1,50 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter4/memento/actualCombat" +) + +func main() { + + //声明负责人对象 + Caretaker := &actualCombat.Caretaker{ + MementoArray: make([]*actualCombat.Memento, 0), + } + + //声明原发器对象 + Originator := new(actualCombat.Originator) + Originator.State = "One" + + fmt.Printf("Originator 当前状态: %s\n", Originator.GetState()) + //添加备忘录 + Caretaker.AddMemento(Originator.CreateMemento()) + + Originator.SetState("Two") + fmt.Printf("Originator 当前状态: %s\n", Originator.GetState()) + //添加备忘录 + Caretaker.AddMemento(Originator.CreateMemento()) + + Originator.SetState("Three") + fmt.Printf("Originator 当前状态: %s\n", Originator.GetState()) + //添加备忘录 + Caretaker.AddMemento(Originator.CreateMemento()) + + //恢复原发器对象的状态 + Originator.RestoreMemento(Caretaker.GetMemento(1)) + fmt.Printf("恢复到状态: %s\n", Originator.GetState()) + //恢复原发器对象的状态 + Originator.RestoreMemento(Caretaker.GetMemento(0)) + fmt.Printf("恢复到状态: %s\n", Originator.GetState()) +} diff --git a/chapter4/memento/main.go b/chapter4/memento/main.go new file mode 100644 index 0000000..2af6020 --- /dev/null +++ b/chapter4/memento/main.go @@ -0,0 +1,46 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter4/memento/example" +) + +func main() { + //声明负责人对象 + Caretaker := &example.Caretaker{ + History: make([]*example.Memento, 0), + } + + //声明原发器对象 + n := example.NewOriginator(100) + + //添加备忘录 + Caretaker.AddMemento(n.CreateMemento()) + n.TenTimes() + fmt.Printf("Originator 当前的值: %d\n", n.Value()) + + //添加备忘录 + Caretaker.AddMemento(n.CreateMemento()) + n.TenTimes() + fmt.Printf("Originator 当前的值: %d\n", n.Value()) + + //恢复原发器对象的值 + n.RestoreMemento(Caretaker.GetMemento(0)) + fmt.Printf("恢复备忘录后 Originator 当前的值: %d\n", n.Value()) +} + +//$ go run main.go +//Originator 当前的值: 1000 +//Originator 当前的值: 10000 +//恢复备忘录后 Originator 当前的值: 100 diff --git a/chapter4/observer/actualCombat/observer.go b/chapter4/observer/actualCombat/observer.go new file mode 100644 index 0000000..ffda0ea --- /dev/null +++ b/chapter4/observer/actualCombat/observer.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//定义观察者接口 +type Observer interface { + Update(string) + GetID() string +} diff --git a/chapter4/observer/actualCombat/product.go b/chapter4/observer/actualCombat/product.go new file mode 100644 index 0000000..fed7f03 --- /dev/null +++ b/chapter4/observer/actualCombat/product.go @@ -0,0 +1,63 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//商品类 +type Product struct { + ObserverList []Observer + name string + inStock bool +} + +//新增商品 +func NewProduct(name string) *Product { + return &Product{ + name: name, + } +} + +//更新库存状态 +func (i *Product) UpdateAvailability() { + fmt.Printf("商品 %s 现在上架了~\n", i.name) + i.inStock = true + i.NotifyAll() +} + +//注册到观察者列表 +func (i *Product) Register(o Observer) { + i.ObserverList = append(i.ObserverList, o) +} + +//从观察者列表删除 +func (i *Product) Deregister(o Observer) { + i.ObserverList = RemoveFromslice(i.ObserverList, o) +} + +//通知所有用户 +func (i *Product) NotifyAll() { + for _, Observer := range i.ObserverList { + Observer.Update(i.name) + } +} + +func RemoveFromslice(ObserverList []Observer, ObserverToRemove Observer) []Observer { + ObserverListLength := len(ObserverList) + for i, Observer := range ObserverList { + if ObserverToRemove.GetID() == Observer.GetID() { + ObserverList[ObserverListLength-1], ObserverList[i] = ObserverList[i], ObserverList[ObserverListLength-1] + return ObserverList[:ObserverListLength-1] + } + } + return ObserverList +} diff --git a/chapter4/observer/actualCombat/subject.go b/chapter4/observer/actualCombat/subject.go new file mode 100644 index 0000000..039e505 --- /dev/null +++ b/chapter4/observer/actualCombat/subject.go @@ -0,0 +1,19 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//主体类 +type Subject interface { + Register(Observer Observer) + Deregister(Observer Observer) + NotifyAll() +} diff --git a/chapter4/observer/actualCombat/user.go b/chapter4/observer/actualCombat/user.go new file mode 100644 index 0000000..01d31a4 --- /dev/null +++ b/chapter4/observer/actualCombat/user.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//定义用户模型 +type User struct { + Id string +} + +//更新 +func (c *User) Update(ProductName string) { + fmt.Printf("发送邮件给用户: %s ,商品: %s 上架啦~ \n", c.Id, ProductName) +} + +//获取编号 +func (c *User) GetID() string { + return c.Id +} diff --git a/chapter4/observer/example/observer.go b/chapter4/observer/example/observer.go new file mode 100644 index 0000000..d99e2fe --- /dev/null +++ b/chapter4/observer/example/observer.go @@ -0,0 +1,67 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +// 要观察和通知的事件 +type Event struct { + Id string +} + +// 观察者接口 +type Observer interface { + Update(event Event) +} + +// 具体观察者 +type ConcreteObserver struct { + name string +} + +//创建一个新的具体观察者对象 +func NewObserver(name string) Observer { + return &ConcreteObserver{name} +} + +// 具体观察者的方法 +func (o *ConcreteObserver) Update(event Event) { + fmt.Printf("ConcreteObserver '%s' received event '%s'\n", o.name, event.Id) +} + +// 抽象主题 +type Subject struct { + ObserverCollection []Observer +} + +// 注册一个新的具体观察者 +func (e *Subject) Register(obs Observer) { + e.ObserverCollection = append(e.ObserverCollection, obs) +} + +// 取消注册具体观察者 +func (e *Subject) Unregister(obs Observer) { + for i := 0; i < len(e.ObserverCollection); i++ { + if obs == e.ObserverCollection[i] { + e.ObserverCollection = append(e.ObserverCollection[:i], e.ObserverCollection[i+1:]...) + } + } +} + +// 通知所有具体观察者集合 +func (e *Subject) NotifyObservers(event Event) { + for i := 0; i < len(e.ObserverCollection); i++ { + e.ObserverCollection[i].Update(event) + } +} diff --git a/chapter4/observer/main-actual-combat.go b/chapter4/observer/main-actual-combat.go new file mode 100644 index 0000000..0f14976 --- /dev/null +++ b/chapter4/observer/main-actual-combat.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/observer/actualCombat" +) + +func main() { + + //声明商品对象 + bookProduct := actualCombat.NewProduct("《Go语言高级开发与实战》") + + ObserverFirst := &actualCombat.User{Id: "shirdonliao@gmail.com"} + ObserverSecond := &actualCombat.User{Id: "barry@gmail.com"} + + //通知第一个用户 + bookProduct.Register(ObserverFirst) + //通知第二个用户 + bookProduct.Register(ObserverSecond) + + //更新库存 + bookProduct.UpdateAvailability() +} + +//$ go run main-actual-combat.go +//商品 《Go语言高级开发与实战》 现在上架了~ +//发送邮件给用户: shirdonliao@gmail.com ,商品: 《Go语言高级开发与实战》 上架啦~ +//发送邮件给用户: barry@gmail.com ,商品: 《Go语言高级开发与实战》 上架啦~ diff --git a/chapter4/observer/main.go b/chapter4/observer/main.go new file mode 100644 index 0000000..cdbdfd3 --- /dev/null +++ b/chapter4/observer/main.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter4/observer/example" + +func main() { + //event := example.Event{"event"} + //observer := example.NewObserver("Barry") + //observer.Update(event) + + notifier := example.Subject{} + observers := []example.Observer{ + example.NewObserver("Barry"), + example.NewObserver("Jack"), + example.NewObserver("Shirdon"), + } + + for i := 0; i < len(observers); i++ { + notifier.Register(observers[i]) + } + notifier.Unregister(observers[1]) + notifier.NotifyObservers(example.Event{"Received an email!"}) +} + +//$ go run main.go +//ConcreteObserver 'Barry' received event 'Received an email!' +//ConcreteObserver 'Shirdon' received event 'Received an email!' diff --git a/chapter4/state/actualCombat/hasMoneyState.go b/chapter4/state/actualCombat/hasMoneyState.go new file mode 100644 index 0000000..8b6ff23 --- /dev/null +++ b/chapter4/state/actualCombat/hasMoneyState.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type HasMoneyState struct { + VendingMachine *VendingMachine +} + +func (i *HasMoneyState) RequestProduct() error { + return fmt.Errorf("Product dispense in progress") +} + +func (i *HasMoneyState) AddProduct(count int) error { + return fmt.Errorf("Product dispense in progress") +} + +func (i *HasMoneyState) InsertMoney(money int) error { + return fmt.Errorf("Product out of stock") +} +func (i *HasMoneyState) DispenseProduct() error { + fmt.Println("Dispensing Product") + i.VendingMachine.productCount = i.VendingMachine.productCount - 1 + if i.VendingMachine.productCount == 0 { + i.VendingMachine.SetState(i.VendingMachine.noProduct) + } else { + i.VendingMachine.SetState(i.VendingMachine.hasProduct) + } + return nil +} diff --git a/chapter4/state/actualCombat/hasProductState.go b/chapter4/state/actualCombat/hasProductState.go new file mode 100644 index 0000000..20e426a --- /dev/null +++ b/chapter4/state/actualCombat/hasProductState.go @@ -0,0 +1,41 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type HasProductState struct { + VendingMachine *VendingMachine +} + +func (i *HasProductState) RequestProduct() error { + if i.VendingMachine.productCount == 0 { + i.VendingMachine.SetState(i.VendingMachine.noProduct) + return fmt.Errorf("No product present") + } + fmt.Printf("Product requestd\n") + i.VendingMachine.SetState(i.VendingMachine.productRequested) + return nil +} + +func (i *HasProductState) AddProduct(count int) error { + fmt.Printf("%d products added\n", count) + i.VendingMachine.IncrementProductCount(count) + return nil +} + +func (i *HasProductState) InsertMoney(money int) error { + return fmt.Errorf("Please select product first") +} +func (i *HasProductState) DispenseProduct() error { + return fmt.Errorf("Please select product first") +} diff --git a/chapter4/state/actualCombat/itemRequestedState.go b/chapter4/state/actualCombat/itemRequestedState.go new file mode 100644 index 0000000..4f8cda5 --- /dev/null +++ b/chapter4/state/actualCombat/itemRequestedState.go @@ -0,0 +1,38 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type ProductRequestedState struct { + VendingMachine *VendingMachine +} + +func (i *ProductRequestedState) RequestProduct() error { + return fmt.Errorf("Product already requested") +} + +func (i *ProductRequestedState) AddProduct(count int) error { + return fmt.Errorf("Product Dispense in progress") +} + +func (i *ProductRequestedState) InsertMoney(money int) error { + if money < i.VendingMachine.productPrice { + fmt.Errorf("Inserted money is less. Please insert %d", i.VendingMachine.productPrice) + } + fmt.Println("Money entered is ok") + i.VendingMachine.SetState(i.VendingMachine.hasMoney) + return nil +} +func (i *ProductRequestedState) DispenseProduct() error { + return fmt.Errorf("Please insert money first") +} diff --git a/chapter4/state/actualCombat/noProductState.go b/chapter4/state/actualCombat/noProductState.go new file mode 100644 index 0000000..333fe94 --- /dev/null +++ b/chapter4/state/actualCombat/noProductState.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +type NoProductState struct { + VendingMachine *VendingMachine +} + +func (i *NoProductState) RequestProduct() error { + return fmt.Errorf("Product out of stock") +} + +func (i *NoProductState) AddProduct(count int) error { + i.VendingMachine.IncrementProductCount(count) + i.VendingMachine.SetState(i.VendingMachine.hasProduct) + return nil +} + +func (i *NoProductState) InsertMoney(money int) error { + return fmt.Errorf("Product out of stock") +} +func (i *NoProductState) DispenseProduct() error { + return fmt.Errorf("Product out of stock") +} diff --git a/chapter4/state/actualCombat/state.go b/chapter4/state/actualCombat/state.go new file mode 100644 index 0000000..c4f3e54 --- /dev/null +++ b/chapter4/state/actualCombat/state.go @@ -0,0 +1,19 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type State interface { + AddProduct(int) error + RequestProduct() error + InsertMoney(money int) error + DispenseProduct() error +} diff --git a/chapter4/state/actualCombat/vendingMachine.go b/chapter4/state/actualCombat/vendingMachine.go new file mode 100644 index 0000000..403c6a2 --- /dev/null +++ b/chapter4/state/actualCombat/vendingMachine.go @@ -0,0 +1,78 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//自动售货机类 +type VendingMachine struct { + hasProduct State + productRequested State + hasMoney State + noProduct State + + currentState State + + productCount int + productPrice int +} + +func NewVendingMachine(productCount, productPrice int) *VendingMachine { + v := &VendingMachine{ + productCount: productCount, + productPrice: productPrice, + } + HasProductState := &HasProductState{ + VendingMachine: v, + } + ProductRequestedState := &ProductRequestedState{ + VendingMachine: v, + } + HasMoneyState := &HasMoneyState{ + VendingMachine: v, + } + NoProductState := &NoProductState{ + VendingMachine: v, + } + + v.SetState(HasProductState) + v.hasProduct = HasProductState + v.productRequested = ProductRequestedState + v.hasMoney = HasMoneyState + v.noProduct = NoProductState + return v +} + +func (v *VendingMachine) RequestProduct() error { + return v.currentState.RequestProduct() +} + +func (v *VendingMachine) AddProduct(count int) error { + return v.currentState.AddProduct(count) +} + +func (v *VendingMachine) InsertMoney(money int) error { + return v.currentState.InsertMoney(money) +} + +func (v *VendingMachine) DispenseProduct() error { + return v.currentState.DispenseProduct() +} + +func (v *VendingMachine) SetState(s State) { + v.currentState = s +} + +func (v *VendingMachine) IncrementProductCount(count int) { + fmt.Printf("Adding %d products\n", count) + v.productCount = v.productCount + count +} diff --git a/chapter4/state/example/state.go b/chapter4/state/example/state.go new file mode 100644 index 0000000..02fe148 --- /dev/null +++ b/chapter4/state/example/state.go @@ -0,0 +1,90 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +// 上下文定义了可以打开和关闭的状态 +type Context struct { + state State +} + +// 初始化上下文 +func NewContext() *Context { + fmt.Println("Context准备好了") + return &Context{NewConcreteStateB()} +} + +// ChangeState 设置上下文的当前状态 +func (c *Context) ChangeState(s State) { + c.state = s +} + +// 按下打开按钮 +func (c *Context) On() { + c.state.On(c) +} + +// 按下关闭按钮 +func (c *Context) Off() { + c.state.Off(c) +} + +// 描述了上下文的内部状态 +type State interface { + On(m *Context) + Off(m *Context) +} + +//ConcreteStateA 描述了打开按钮的状态 +type ConcreteStateA struct { + context Context +} + +// 创建一个新的具体状态A +func NewConcreteStateA() State { + return &ConcreteStateA{} +} + +// 具体状态A的打开方法 +func (cs *ConcreteStateA) On(m *Context) { + fmt.Println("已经打开了~") +} + +// 将状态从打开切换到关闭 +func (cs *ConcreteStateA) Off(m *Context) { + fmt.Println("将状态从打开切换到关闭~") + m.ChangeState(NewConcreteStateB()) +} + +// ConcreteStateB 描述关闭按钮状态 +type ConcreteStateB struct { + context Context +} + +// NewConcreteStateB 创建一个新的具体状态B +func NewConcreteStateB() State { + return &ConcreteStateB{} +} + +// 将状态从关闭切换到打开 +func (cs *ConcreteStateB) On(m *Context) { + fmt.Println("将状态从关闭切换到打开~") + m.ChangeState(NewConcreteStateA()) +} + +// 具体状态B的关闭方法 +func (cs *ConcreteStateB) Off(m *Context) { + fmt.Println("已经关闭~") +} diff --git a/chapter4/state/main-actual-combat.go b/chapter4/state/main-actual-combat.go new file mode 100644 index 0000000..34e739d --- /dev/null +++ b/chapter4/state/main-actual-combat.go @@ -0,0 +1,58 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter4/state/actualCombat" + "log" +) + +func main() { + //声明自动售货机 + VendingMachine := actualCombat.NewVendingMachine(1, 10) + + //请求商品 + err := VendingMachine.RequestProduct() + if err != nil { + log.Fatalf(err.Error()) + } + + //向自动售货机放入10元钱 + err = VendingMachine.InsertMoney(10) + if err != nil { + log.Fatalf(err.Error()) + } + + //向自动售货机分配商品 + err = VendingMachine.DispenseProduct() + if err != nil { + log.Fatalf(err.Error()) + } + + fmt.Println() + + //向自动售货机添加2个商品 + err = VendingMachine.AddProduct(2) + if err != nil { + log.Fatalf(err.Error()) + } + + fmt.Println() +} + +//$ go run main-actual-combat.go +//Product requestd +//Money entered is ok +//Dispensing Product +// +//Adding 2 products diff --git a/chapter4/state/main.go b/chapter4/state/main.go new file mode 100644 index 0000000..aea9328 --- /dev/null +++ b/chapter4/state/main.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter4/state/example" + +func main() { + context := example.NewContext() + context.Off() + context.On() + context.On() + context.Off() +} + +//$ go run main.go +//Context准备好了 +//已经关闭~ +//将状态从关闭切换到打开~ +//已经打开了~ +//将状态从打开切换到关闭~ diff --git a/chapter4/strategy/actualCombat/algorithmType.go b/chapter4/strategy/actualCombat/algorithmType.go new file mode 100644 index 0000000..2663577 --- /dev/null +++ b/chapter4/strategy/actualCombat/algorithmType.go @@ -0,0 +1,16 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type AlgorithmType interface { + Delete(c *Cache) +} diff --git a/chapter4/strategy/actualCombat/cache.go b/chapter4/strategy/actualCombat/cache.go new file mode 100644 index 0000000..bd7da6c --- /dev/null +++ b/chapter4/strategy/actualCombat/cache.go @@ -0,0 +1,50 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +type Cache struct { + storage map[string]string + AlgorithmType AlgorithmType + capacity int + maxCapacity int +} + +func InitCache(e AlgorithmType) *Cache { + storage := make(map[string]string) + return &Cache{ + storage: storage, + AlgorithmType: e, + capacity: 0, + maxCapacity: 2, + } +} + +func (c *Cache) SetAlgorithmType(e AlgorithmType) { + c.AlgorithmType = e +} + +func (c *Cache) Add(key, value string) { + if c.capacity == c.maxCapacity { + c.Delete() + } + c.capacity++ + c.storage[key] = value +} + +func (c *Cache) Get(key string) { + delete(c.storage, key) +} + +func (c *Cache) Delete() { + c.AlgorithmType.Delete(c) + c.capacity-- +} diff --git a/chapter4/strategy/actualCombat/fifo.go b/chapter4/strategy/actualCombat/fifo.go new file mode 100644 index 0000000..6a11fc9 --- /dev/null +++ b/chapter4/strategy/actualCombat/fifo.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//FIFO算法类型 +type Fifo struct { +} + +//删除缓存 +func (l *Fifo) Delete(c *Cache) { + fmt.Println("Deleting by fifo strategy") +} diff --git a/chapter4/strategy/actualCombat/lfu.go b/chapter4/strategy/actualCombat/lfu.go new file mode 100644 index 0000000..43b2df8 --- /dev/null +++ b/chapter4/strategy/actualCombat/lfu.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//LFU算法类型 +type Lfu struct { +} + +//删除缓存 +func (l *Lfu) Delete(c *Cache) { + fmt.Println("Deleting by lfu strategy") +} diff --git a/chapter4/strategy/actualCombat/lru.go b/chapter4/strategy/actualCombat/lru.go new file mode 100644 index 0000000..4161a2b --- /dev/null +++ b/chapter4/strategy/actualCombat/lru.go @@ -0,0 +1,23 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//LRU算法类型 +type Lru struct { +} + +//删除缓存 +func (l *Lru) Delete(c *Cache) { + fmt.Println("Deleting by lru strategy") +} diff --git a/chapter4/strategy/example/strategy.go b/chapter4/strategy/example/strategy.go new file mode 100644 index 0000000..b76dba5 --- /dev/null +++ b/chapter4/strategy/example/strategy.go @@ -0,0 +1,67 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +//策略接口 +type Strategy interface { + Execute() +} + +// 具体策略 A +type strategyA struct { +} + +// 具体策略 A 的方法 +func (s *strategyA) Execute() { + fmt.Println("执行策略 A") +} + +//具体策略B +type strategyB struct { +} + +//具体策略B的方法 +func (s *strategyB) Execute() { + fmt.Println("执行策略 B") +} + +//上下文 +type Context struct { + strategy Strategy +} + +//设置上下文执行的策略 +func (c *Context) SetStrategy(strategy Strategy) { + c.strategy = strategy +} + +//上下文的方法 +func (c *Context) Execute() { + c.strategy.Execute() +} + +//创建策略 A 的新对象 +func NewStrategyA() Strategy { + return &strategyA{} +} + +//创建策略 B 的新对象 +func NewStrategyB() Strategy { + return &strategyB{} +} + +//创建一个新的上下文对象 +func NewContext() *Context { + return &Context{} +} diff --git a/chapter4/strategy/main-actual-combat.go b/chapter4/strategy/main-actual-combat.go new file mode 100644 index 0000000..8602016 --- /dev/null +++ b/chapter4/strategy/main-actual-combat.go @@ -0,0 +1,50 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/strategy/actualCombat" +) + +func main() { + //声明Lfu对象 + lfu := &actualCombat.Lfu{} + //初始化缓存对象 + cache := actualCombat.InitCache(lfu) + + //添加缓存 + cache.Add("one", "1") + cache.Add("two", "2") + + cache.Add("three", "3") + + //声明Lru对象 + lru := &actualCombat.Lru{} + //设置lru算法类型 + cache.SetAlgorithmType(lru) + + //添加缓存 + cache.Add("four", "4") + + //声明Fifo对象 + fifo := &actualCombat.Fifo{} + //设置Fifo算法类型 + cache.SetAlgorithmType(fifo) + + //添加缓存 + cache.Add("five", "5") +} + +//$ go run main-actual-combat.go +//Deleting by lfu strategy +//Deleting by lru strategy +//Deleting by fifo strategy diff --git a/chapter4/strategy/main.go b/chapter4/strategy/main.go new file mode 100644 index 0000000..495cfc6 --- /dev/null +++ b/chapter4/strategy/main.go @@ -0,0 +1,28 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/strategy/example" +) + +func main() { + strategyB := example.NewStrategyB() + context := example.NewContext() + context.SetStrategy(strategyB) + strategyA := example.NewStrategyA() + context.SetStrategy(strategyA) + context.Execute() +} + +//$ go run main.go +//执行策略 A diff --git a/chapter4/templateMethod/actualCombat/email.go b/chapter4/templateMethod/actualCombat/email.go new file mode 100644 index 0000000..38b54cf --- /dev/null +++ b/chapter4/templateMethod/actualCombat/email.go @@ -0,0 +1,42 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//邮箱类 +type Email struct { + Otp +} + +func (s *Email) GenRandomOTP(len int) string { + randomOTP := "3699" + fmt.Printf("EMAIL: 生成随机验证码:%s\n", randomOTP) + return randomOTP +} + +func (s *Email) SaveOTPCache(otp string) { + fmt.Printf("EMAIL: 保存验证码:%s 到缓存\n", otp) +} + +func (s *Email) GetMessage(otp string) string { + return "登录的短信验证码是:" + otp +} + +func (s *Email) SendNotification(message string) error { + fmt.Printf("EMAIL: 发送消息:%s\n", message) + return nil +} + +func (s *Email) Publish() { + fmt.Printf("EMAIL:发布完成\n") +} diff --git a/chapter4/templateMethod/actualCombat/otp.go b/chapter4/templateMethod/actualCombat/otp.go new file mode 100644 index 0000000..92908b3 --- /dev/null +++ b/chapter4/templateMethod/actualCombat/otp.go @@ -0,0 +1,40 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//定义一次性密码接口 +type IOtp interface { + GenRandomOTP(int) string + SaveOTPCache(string) + GetMessage(string) string + SendNotification(string) error + Publish() +} + +//定义一次性密码类 +type Otp struct { + IOtp IOtp +} + +//生成验证码并发送 +func (o *Otp) GenAndSendOTP(otpLength int) error { + //生成随机验证码 + otp := o.IOtp.GenRandomOTP(otpLength) + o.IOtp.SaveOTPCache(otp) + message := o.IOtp.GetMessage(otp) + err := o.IOtp.SendNotification(message) + if err != nil { + return err + } + o.IOtp.Publish() + return nil +} diff --git a/chapter4/templateMethod/actualCombat/sms.go b/chapter4/templateMethod/actualCombat/sms.go new file mode 100644 index 0000000..3876804 --- /dev/null +++ b/chapter4/templateMethod/actualCombat/sms.go @@ -0,0 +1,42 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//短信类 +type Sms struct { + Otp +} + +func (s *Sms) GenRandomOTP(len int) string { + randomOTP := "1688" + fmt.Printf("SMS: 生成随机验证码:%s\n", randomOTP) + return randomOTP +} + +func (s *Sms) SaveOTPCache(otp string) { + fmt.Printf("SMS: 保存验证码:%s 到缓存\n", otp) +} + +func (s *Sms) GetMessage(otp string) string { + return "登录的短信验证码是:" + otp +} + +func (s *Sms) SendNotification(message string) error { + fmt.Printf("SMS: 发送消息:%s\n", message) + return nil +} + +func (s *Sms) Publish() { + fmt.Printf("SMS: 发布完成\n") +} diff --git a/chapter4/templateMethod/example/templateMethod.go b/chapter4/templateMethod/example/templateMethod.go new file mode 100644 index 0000000..5c35fa7 --- /dev/null +++ b/chapter4/templateMethod/example/templateMethod.go @@ -0,0 +1,78 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import ( + "fmt" +) + +// 抽象类接口 +type AbstractClassInterface interface { + Step1() + Step2() + Step3() +} + +// 抽象类 +type AbstractClass struct { + AbstractClassInterface +} + +// 初始化抽象类对象 +func NewAbstractClass(aci AbstractClassInterface) *AbstractClass { + return &AbstractClass{aci} +} + +// 模版方法 +func (cc *AbstractClass) TemplateMethod() { + cc.Step1() + cc.Step2() + cc.Step3() +} + +// 具体类A +type ConcreteClassA struct { +} + +// 具体类A的方法1 +func (cc *ConcreteClassA) Step1() { + fmt.Println("ConcreteClassA Step1") +} + +// 具体类A的方法2 +func (cc *ConcreteClassA) Step2() { + fmt.Println("ConcreteClassA Step2") +} + +// 具体类A的方法3 +func (cc *ConcreteClassA) Step3() { + fmt.Println("ConcreteClassA Step3") +} + +// 具体类B +type ConcreteClassB struct { +} + +// 具体类B的方法1 +func (cc *ConcreteClassB) Step1() { + fmt.Println("ConcreteClassB Step1") +} + +// 具体类B的方法2 +func (cc *ConcreteClassB) Step2() { + fmt.Println("ConcreteClassB Step2") +} + +// 具体类B的方法3 +func (cc *ConcreteClassB) Step3() { + fmt.Println("ConcreteClassB Step3") +} diff --git a/chapter4/templateMethod/main-actual-combat.go b/chapter4/templateMethod/main-actual-combat.go new file mode 100644 index 0000000..991ec55 --- /dev/null +++ b/chapter4/templateMethod/main-actual-combat.go @@ -0,0 +1,47 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter4/templateMethod/actualCombat" +) + +func main() { + //创建短信对象 + smsOTP := &actualCombat.Sms{} + o := actualCombat.Otp{ + IOtp: smsOTP, + } + //生成短信验证码并发送 + o.GenAndSendOTP(4) + + fmt.Println("") + //创建邮件对象 + EmailOTP := &actualCombat.Email{} + o = actualCombat.Otp{ + IOtp: EmailOTP, + } + //生成邮件验证码并发送 + o.GenAndSendOTP(4) +} + +//$ go run main-actual-combat.go +//SMS: 生成随机验证码:1688 +//SMS: 保存验证码:1688 到缓存 +//SMS: 发送消息:登录的短信验证码是:1688 +//SMS: 发布完成 +// +//EMAIL: 生成随机验证码:3699 +//EMAIL: 保存验证码:3699 到缓存 +//EMAIL: 发送消息:登录的短信验证码是:3699 +//EMAIL:发布完成 diff --git a/chapter4/templateMethod/main.go b/chapter4/templateMethod/main.go new file mode 100644 index 0000000..8817fcf --- /dev/null +++ b/chapter4/templateMethod/main.go @@ -0,0 +1,29 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter4/templateMethod/example" + +func main() { + concreteClassA := example.NewAbstractClass(&example.ConcreteClassA{}) + concreteClassA.TemplateMethod() + concreteClassB := example.NewAbstractClass(&example.ConcreteClassB{}) + concreteClassB.TemplateMethod() +} + +//$ go run main.go +//ConcreteClassA Step1 +//ConcreteClassA Step2 +//ConcreteClassA Step3 +//ConcreteClassB Step1 +//ConcreteClassB Step2 +//ConcreteClassB Step3 diff --git a/chapter4/visitor/actualCombat/circle.go b/chapter4/visitor/actualCombat/circle.go new file mode 100644 index 0000000..7ade85a --- /dev/null +++ b/chapter4/visitor/actualCombat/circle.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//圆形 +type Circle struct { + Radius float32 +} + +func (c *Circle) Accept(v Visitor) { + v.VisitForCircle(c) +} + +func (c *Circle) GetType() string { + return "Circle" +} diff --git a/chapter4/visitor/actualCombat/middleCoordinates.go b/chapter4/visitor/actualCombat/middleCoordinates.go new file mode 100644 index 0000000..675f64b --- /dev/null +++ b/chapter4/visitor/actualCombat/middleCoordinates.go @@ -0,0 +1,35 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import "fmt" + +//中点坐标计算器 +type MiddleCoordinates struct { + x int + y int +} + +func (a *MiddleCoordinates) VisitForSquare(s *Square) { + //...省略具体逻辑 + fmt.Println("计算正方形的中点坐标") +} + +func (a *MiddleCoordinates) VisitForCircle(c *Circle) { + //...省略具体逻辑 + fmt.Println("计算圆形的中点坐标") +} + +func (a *MiddleCoordinates) VisitForRectangle(t *Rectangle) { + //...省略具体逻辑 + fmt.Println("计算矩形的中点坐标") +} diff --git a/chapter4/visitor/actualCombat/perimeterCalculator.go b/chapter4/visitor/actualCombat/perimeterCalculator.go new file mode 100644 index 0000000..bcc4010 --- /dev/null +++ b/chapter4/visitor/actualCombat/perimeterCalculator.go @@ -0,0 +1,39 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +import ( + "fmt" +) + +//具体访问者——周长计算器 +type PerimeterCalculator struct { + perimeter float32 +} + +func (a *PerimeterCalculator) VisitForSquare(s *Square) { + var perimeter float32 + perimeter = 4 * s.Side + fmt.Printf("计算正方形的周长:%f \n", perimeter) +} + +func (a *PerimeterCalculator) VisitForCircle(c *Circle) { + var perimeter float32 + perimeter = 3.14 * 2 * c.Radius + fmt.Printf("计算圆形的周长:%f \n", perimeter) +} + +func (a *PerimeterCalculator) VisitForRectangle(r *Rectangle) { + var perimeter float32 + perimeter = 2*r.B + 2*r.L + fmt.Printf("计算矩形的周长:%f \n", perimeter) +} diff --git a/chapter4/visitor/actualCombat/rectangle.go b/chapter4/visitor/actualCombat/rectangle.go new file mode 100644 index 0000000..5a7e0b2 --- /dev/null +++ b/chapter4/visitor/actualCombat/rectangle.go @@ -0,0 +1,26 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//矩形 +type Rectangle struct { + L float32 + B float32 +} + +func (t *Rectangle) Accept(v Visitor) { + v.VisitForRectangle(t) +} + +func (t *Rectangle) GetType() string { + return "Rectangle" +} diff --git a/chapter4/visitor/actualCombat/shape.go b/chapter4/visitor/actualCombat/shape.go new file mode 100644 index 0000000..6096fdc --- /dev/null +++ b/chapter4/visitor/actualCombat/shape.go @@ -0,0 +1,18 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//形状接口 +type Shape interface { + GetType() string + Accept(Visitor) +} diff --git a/chapter4/visitor/actualCombat/square.go b/chapter4/visitor/actualCombat/square.go new file mode 100644 index 0000000..6c39d87 --- /dev/null +++ b/chapter4/visitor/actualCombat/square.go @@ -0,0 +1,25 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//具体元素——正方形 +type Square struct { + Side float32 +} + +func (s *Square) Accept(v Visitor) { + v.VisitForSquare(s) +} + +func (s *Square) GetType() string { + return "Square" +} diff --git a/chapter4/visitor/actualCombat/visitor.go b/chapter4/visitor/actualCombat/visitor.go new file mode 100644 index 0000000..c326e35 --- /dev/null +++ b/chapter4/visitor/actualCombat/visitor.go @@ -0,0 +1,19 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +//访问者接口 +type Visitor interface { + VisitForSquare(*Square) + VisitForCircle(*Circle) + VisitForRectangle(*Rectangle) +} diff --git a/chapter4/visitor/example/visitor.go b/chapter4/visitor/example/visitor.go new file mode 100644 index 0000000..fdb9771 --- /dev/null +++ b/chapter4/visitor/example/visitor.go @@ -0,0 +1,81 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +import "fmt" + +// 元素定义了一个接受访问者的接口 +type Element interface { + Accept(v Visitor) +} + +// 具体元素A +type ConcreteElementA struct { +} + +// 具体元素A的方法 +func (t *ConcreteElementA) FeatureA() string { + return "ConcreteElementA" +} + +// Accept 接受访问者 +func (t *ConcreteElementA) Accept(v Visitor) { + v.VisitConcreteElementA(t) +} + +// 具体元素B +type ConcreteElementB struct { +} + +// 具体元素B的方法 +func (t *ConcreteElementB) FeatureB() string { + return "ConcreteElementB" +} + +// Accept 接受访问者 +func (t *ConcreteElementB) Accept(v Visitor) { + v.VisitConcreteElementB(t) +} + +// 访问者接口 +type Visitor interface { + VisitConcreteElementA(e *ConcreteElementA) + VisitConcreteElementB(e *ConcreteElementB) +} + +// 具体访问者A +type ConcreteVisitorA struct { +} + +// 具体访问者A的方法 +func (v *ConcreteVisitorA) VisitConcreteElementA(e *ConcreteElementA) { + fmt.Printf("具体访问者A %v\n", e.FeatureA()) +} + +// 具体访问者A的方法 +func (v *ConcreteVisitorA) VisitConcreteElementB(e *ConcreteElementB) { + fmt.Printf("具体访问者A %v\n", e.FeatureB()) +} + +// 具体访问者B +type ConcreteVisitorB struct { +} + +// 具体访问者B的方法 +func (v *ConcreteVisitorB) VisitConcreteElementA(e *ConcreteElementA) { + fmt.Printf("具体访问者B %v\n", e.FeatureA()) +} + +// 具体访问者B的方法 +func (v *ConcreteVisitorB) VisitConcreteElementB(e *ConcreteElementB) { + fmt.Printf("具体访问者B %v\n", e.FeatureB()) +} diff --git a/chapter4/visitor/main-actual-combat.go b/chapter4/visitor/main-actual-combat.go new file mode 100644 index 0000000..bbdd7ca --- /dev/null +++ b/chapter4/visitor/main-actual-combat.go @@ -0,0 +1,57 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "fmt" + +import ( + "github.com/shirdonl/goDesignPattern/chapter4/visitor/actualCombat" +) + +func main() { + //声明边长为1的正方形 + Square := &actualCombat.Square{Side: 1} + //声明半径为6的圆形 + Circle := &actualCombat.Circle{Radius: 6} + //声明长为8,宽为6的矩形 + Rectangle := &actualCombat.Rectangle{L: 8, B: 6} + + //声明周长计算器 + PerimeterCalculator := &actualCombat.PerimeterCalculator{} + + //正方形计算周长 + Square.Accept(PerimeterCalculator) + //圆形计算周长 + Circle.Accept(PerimeterCalculator) + //矩形计算周长 + Rectangle.Accept(PerimeterCalculator) + Square.GetType() + + fmt.Println() + //声明中点坐标计算器 + MiddleCoordinates := &actualCombat.MiddleCoordinates{} + //获取正方形中点坐标 + Square.Accept(MiddleCoordinates) + //获取圆形中点坐标 + Circle.Accept(MiddleCoordinates) + //获取矩形中点坐标 + Rectangle.Accept(MiddleCoordinates) +} + +//$ go run main-actual-combat.go +//计算正方形的周长:4.000000 +//计算圆形的周长:37.680000 +//计算矩形的周长:28.000000 +// +//计算正方形的中点坐标 +//计算圆形的中点坐标 +//计算矩形的中点坐标 diff --git a/chapter4/visitor/main.go b/chapter4/visitor/main.go new file mode 100644 index 0000000..3a6b9b9 --- /dev/null +++ b/chapter4/visitor/main.go @@ -0,0 +1,34 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "github.com/shirdonl/goDesignPattern/chapter4/visitor/example" + +func main() { + //声明具体元素A + concreteElementA := &example.ConcreteElementA{} + //调用具体元素A的方法 + concreteElementA.FeatureA() + //具体元素A接受具体访问者A + concreteElementA.Accept(&example.ConcreteVisitorA{}) + + //声明具体元素B + concreteElementB := &example.ConcreteElementB{} + //调用具体元素B的方法 + concreteElementB.FeatureB() + //具体元素B接受具体访问者B + concreteElementB.Accept(&example.ConcreteVisitorB{}) +} + +//$ go run main.go +//具体访问者A ConcreteElementA +//具体访问者B ConcreteElementB diff --git a/chapter5/ddd/app/internal/tab/mysqlRepo.go b/chapter5/ddd/app/internal/tab/mysqlRepo.go new file mode 100644 index 0000000..7ae752a --- /dev/null +++ b/chapter5/ddd/app/internal/tab/mysqlRepo.go @@ -0,0 +1,26 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package tab + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter6/ddd/app/workplace/collection/tab" +) + +//这里是一个 MySQL 实现 +type MysqlRepo struct { +} + +func (r *MysqlRepo) Add(t *tab.Tab) error { + // ... + return fmt.Errorf("error: %s %s", tab.ErrRepoAdd, "a more detailed reason here") +} diff --git a/chapter5/ddd/app/workplace/collection/collection.go b/chapter5/ddd/app/workplace/collection/collection.go new file mode 100644 index 0000000..1788e4d --- /dev/null +++ b/chapter5/ddd/app/workplace/collection/collection.go @@ -0,0 +1,87 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package collection + +import ( + "github.com/shirdonl/goDesignPattern/chapter6/ddd/app/workplace/collection/tab" + "time" +) + +// Collection 代表一个集合 +type Collection struct { + ID int + Name string + Tabs []*tab.Tab + Created time.Time + Updated time.Time +} + +// New 返回第一次创建的集合 +func New(id int, name string) *Collection { + return &Collection{ + ID: id, + Name: name, + Tabs: make([]*tab.Tab, 0), + Created: time.Now(), + } +} + +// Rename重命名集合 +func (c *Collection) Rename(name string) { + c.Name = name + c.Updated = time.Now() +} + +// AddTabs 将Tab添加到集合 +func (c *Collection) AddTabs(tabs ...*tab.Tab) { + c.Tabs = append(c.Tabs, tabs...) + c.Updated = time.Now() +} + +// RemoveTab 如果标签存在,则删除它 +func (c *Collection) RemoveTab(id int) bool { + for i, t := range c.Tabs { + if t.ID == id { + c.Tabs[i] = c.Tabs[len(c.Tabs)-1] + c.Tabs[len(c.Tabs)-1] = nil + c.Tabs = c.Tabs[:len(c.Tabs)-1] + c.Updated = time.Now() + return true + } + } + + return false +} + +// FindTab 如果存在则返回一个标签 +func (c *Collection) FindTab(id int) (*tab.Tab, bool) { + for _, t := range c.Tabs { + if t.ID == id { + return t, true + } + } + + return nil, false +} + +// UpdateTab 更新标签(如果存在) +func (c *Collection) UpdateTab(t *tab.Tab) bool { + for i, tb := range c.Tabs { + if tb.ID == t.ID { + c.Tabs[i] = t + c.Updated = time.Now() + return true + } + } + + return false +} diff --git a/chapter5/ddd/app/workplace/collection/tab/repo.go b/chapter5/ddd/app/workplace/collection/tab/repo.go new file mode 100644 index 0000000..0bb5bef --- /dev/null +++ b/chapter5/ddd/app/workplace/collection/tab/repo.go @@ -0,0 +1,41 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package tab + +import "errors" + +var ( + //存储库返回的错误 + ErrRepoNextID = errors.New("tab: could not return next id") + ErrRepoList = errors.New("tab: could not list") + ErrNotFound = errors.New("tab: could not find") + ErrRepoGet = errors.New("tab: could not get") + ErrRepoAdd = errors.New("tab: could not add") + ErrRepoRemove = errors.New("tab: could not remove") +) + +type ID int + +type Repo interface { + //NextID 返回下一个空闲 ID 并在失败时返回错误 + NextID() (ID, error) + // 列表返回一个选项卡切片并在失败的情况下返回一个错误 + List() ([]*Tab, error) + // Find 返回一个 tab 或者 nil ,如果它没有找到并且在失败的情况下,则返回一个错误 + Find(ID) (*Tab, error) + // 如果未找到或失败,则获取返回选项卡和错误 + Get(ID) (*Tab, error) + // 添加持久化选项卡(已经存在或不存在)并在失败时返回错误 + Add(*Tab) error + // 删除选项卡并返回并在未找到或失败的情况下出错 + Remove(ID) error +} diff --git a/chapter5/ddd/app/workplace/collection/tab/tab.go b/chapter5/ddd/app/workplace/collection/tab/tab.go new file mode 100644 index 0000000..92c3674 --- /dev/null +++ b/chapter5/ddd/app/workplace/collection/tab/tab.go @@ -0,0 +1,48 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package tab + +import ( + "time" +) + +// Tab 代表一个标签 +type Tab struct { + ID int + Title Title + Description string + Icon string + Link string + Created time.Time + Updated time.Time +} + +// New 返回第一次创建的标签 +func New(id int, title Title, description string, icon string, link string) *Tab { + return &Tab{ + ID: id, + Title: title, + Description: description, + Icon: icon, + Link: link, + Created: time.Now(), + } +} + +// Update 使用新属性更新标签 +func (t *Tab) Update(title Title, description string, icon string, link string) { + t.Title = title + t.Description = description + t.Icon = icon + t.Link = link + t.Updated = time.Now() +} diff --git a/chapter5/ddd/app/workplace/collection/tab/title.go b/chapter5/ddd/app/workplace/collection/tab/title.go new file mode 100644 index 0000000..991e95d --- /dev/null +++ b/chapter5/ddd/app/workplace/collection/tab/title.go @@ -0,0 +1,77 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package tab + +import ( + "encoding/json" + "errors" + "fmt" + "strings" +) + +const ( + minTitleLength = 1 + maxTitleLength = 50 +) + +var ( + // 给出无效标题时使用的错误 + ErrInvalidTitle = errors.New("tab: could not use invalid title") + ErrTitleTooShort = fmt.Errorf("%s: min length allowed is %d", ErrInvalidTitle, minTitleLength) + ErrTitleTooLong = fmt.Errorf("%s: max length allowed is %d", ErrInvalidTitle, maxTitleLength) +) + +// Title 代表标签标题 +type Title string + +// NewTitle 返回标题和错误 +func NewTitle(d string) (Title, error) { + switch l := len(strings.TrimSpace(d)); { + case l < minTitleLength: + return "", ErrTitleTooShort + case l > maxTitleLength: + return "", ErrTitleTooLong + default: + return Title(d), nil + } +} + +// String 返回标题的字符串表示 +func (t Title) String() string { + return string(t) +} + +// Equals 如果标题相等,则返回 true +func (t Title) Equals(t2 Title) bool { + return t.String() == t2.String() +} + +//添加标签请求 +type addTabReq struct { + Title Title `json:"tab_title"` +} + +//解码JSON请求正文 +func (r *addTabReq) UnmarshalJSON(data []byte) error { + type clone addTabReq + var req clone + if err := json.Unmarshal(data, &req); err != nil { + return err + } + + var err error + if r.Title, err = NewTitle(req.Title.String()); err != nil { + return err + } + + return nil +} diff --git a/chapter5/ddd/app/workplace/workplace.go b/chapter5/ddd/app/workplace/workplace.go new file mode 100644 index 0000000..12f6f6e --- /dev/null +++ b/chapter5/ddd/app/workplace/workplace.go @@ -0,0 +1,78 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package workspace + +import ( + "github.com/shirdonl/goDesignPattern/chapter6/ddd/app/workplace/collection" + "time" +) + +// 工作区 +type Workspace struct { + ID int + Name string + CustomerID int + Collections []*collection.Collection + Created time.Time + Updated time.Time +} + +// 返回第一次创建的工作区 +func New(id int, name string, customerID int) *Workspace { + return &Workspace{ + ID: id, + Name: name, + CustomerID: customerID, + Collections: make([]*collection.Collection, 0), + Created: time.Now(), + } +} + +// 更改工作区的名称 +func (w *Workspace) Rename(name string) { + w.Name = name + w.Updated = time.Now() +} + +// 添加一个集合 +func (w *Workspace) AddCollections(collections ...*collection.Collection) { + w.Collections = append(w.Collections, collections...) + w.Updated = time.Now() +} + +// 如果集合存在,则删除它 +func (w *Workspace) RemoveCollection(id int) bool { + for i, coll := range w.Collections { + if coll.ID == id { + w.Collections[i] = w.Collections[len(w.Collections)-1] + w.Collections[len(w.Collections)-1] = nil + w.Collections = w.Collections[:len(w.Collections)-1] + w.Updated = time.Now() + return true + } + } + + return false +} + +// 重命名集合(如果存在) +func (w *Workspace) RenameCollection(id int, name string) bool { + for _, coll := range w.Collections { + if coll.ID == id { + coll.Rename(name) + w.Updated = time.Now() + return true + } + } + + return false +} diff --git a/chapter5/nullObject/actualCombat/nullObject.go b/chapter5/nullObject/actualCombat/nullObject.go new file mode 100644 index 0000000..fcfa57e --- /dev/null +++ b/chapter5/nullObject/actualCombat/nullObject.go @@ -0,0 +1,131 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import "fmt" + +//学院 +type college struct { + departments []department +} + +//添加部门 +func (c *college) addDepartment(departmentName string, numOfProfessors int) { + if departmentName == "computerscience" { + computerScienceDepartment := &computerscience{numberOfProfessors: numOfProfessors} + c.departments = append(c.departments, computerScienceDepartment) + } + if departmentName == "mechanical" { + mechanicalDepartment := &mechanical{numberOfProfessors: numOfProfessors} + c.departments = append(c.departments, mechanicalDepartment) + } + return +} + +//获取部门 +func (c *college) getDepartment(departmentName string) department { + for _, department := range c.departments { + if department.getName() == departmentName { + return department + } + } + //如果部门不存在,则返回空部门 + return &nullDepartment{} +} + +//部门接口 +type department interface { + getNumberOfProfessors() int + getName() string +} + +//计算机科学系 +type computerscience struct { + numberOfProfessors int +} + +//获取计算机科学系教授数量 +func (c *computerscience) getNumberOfProfessors() int { + return c.numberOfProfessors +} + +//获取部门名字 +func (c *computerscience) getName() string { + return "computerscience" +} + +//机械系 +type mechanical struct { + numberOfProfessors int +} + +//获取机械系教授数量 +func (c *mechanical) getNumberOfProfessors() int { + return c.numberOfProfessors +} + +//获取部门名字 +func (c *mechanical) getName() string { + return "mechanical" +} + +//空对象 +type nullDepartment struct { + numberOfProfessors int +} + +//获取空对象教授数量 +func (c *nullDepartment) getNumberOfProfessors() int { + return 0 +} + +//获取空对象名字 +func (c *nullDepartment) getName() string { + return "" +} + +//创建学院1 +func createCollege1() *college { + college := &college{} + college.addDepartment("computerscience", 0) + college.addDepartment("mechanical", 2) + return college +} + +//创建学院2 +func createCollege2() *college { + college := &college{} + college.addDepartment("computerscience", 3) + return college +} + +func main() { + college1 := createCollege1() + college2 := createCollege2() + totalProfessors := 0 + departmentArray := []string{"computerscience", "mechanical", "chinese", "computer"} + for _, deparmentName := range departmentArray { + d := college1.getDepartment(deparmentName) + totalProfessors += d.getNumberOfProfessors() + } + fmt.Printf("学院1的教授数量为: %d\n", totalProfessors) + totalProfessors = 0 + for _, deparmentName := range departmentArray { + d := college2.getDepartment(deparmentName) + totalProfessors += d.getNumberOfProfessors() + } + fmt.Printf("学院2的教授数量为: %d\n", totalProfessors) +} + +//$ go run nullObject.go +//学院1的教授数量为: 2 +//学院2的教授数量为: 3 diff --git a/chapter5/nullObject/example/.env b/chapter5/nullObject/example/.env new file mode 100644 index 0000000..dcd91c4 --- /dev/null +++ b/chapter5/nullObject/example/.env @@ -0,0 +1 @@ +RealObject=1 \ No newline at end of file diff --git a/chapter5/nullObject/example/nullObject.go b/chapter5/nullObject/example/nullObject.go new file mode 100644 index 0000000..8657841 --- /dev/null +++ b/chapter5/nullObject/example/nullObject.go @@ -0,0 +1,62 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "errors" + "fmt" + "github.com/stretchr/testify/mock" + "os" +) + +//抽象对象 +type AbstractObject struct { + mock.Mock +} + +//方法 +func (m *AbstractObject) Request(str string) (string, error) { + args := m.Called(str) + return args.String(0), args.Error(1) +} + +//空对象 +type NullObject struct { + AbstractObject +} + +func (w *NullObject) Request(str string) (string, error) { + return "null", errors.New("not implemented yet!") +} + +//真实对象 +type RealObject struct { + AbstractObject +} + +func (w *RealObject) Request(str string) (string, error) { + return str, nil +} + +func main() { + os.Setenv("RealObject", "true") + var realObject *RealObject + var nullObject *NullObject + _, realObjectFlagExists := os.LookupEnv("RealObject") + if realObjectFlagExists { + realObject = &RealObject{} + fmt.Println(realObject.Request("real")) + } else { + nullObject = &NullObject{} + fmt.Println(nullObject.Request("null")) + } +} diff --git a/chapter5/specification/actualCombat/specification.go b/chapter5/specification/actualCombat/specification.go new file mode 100644 index 0000000..56b4d92 --- /dev/null +++ b/chapter5/specification/actualCombat/specification.go @@ -0,0 +1,153 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package actualCombat + +// 发票数据对象 +type Invoice struct { + Day int + Notice int + IsSent bool +} + +// 数据规格接口 +type Specification interface { + IsSatisfiedBy(Invoice) bool + And(Specification) Specification + Or(Specification) Specification + Not() Specification + Relate(Specification) +} + +// 组合规格 +type CompositeSpecification struct { + Specification +} + +// 检查规格 +func (cs *CompositeSpecification) IsSatisfiedBy(in Invoice) bool { + return false +} + +// 规格与操作 +func (cs *CompositeSpecification) And(spec Specification) Specification { + a := &AndSpecification{ + cs.Specification, spec, + } + a.Relate(a) + return a +} + +// 规格或操作 +func (cs *CompositeSpecification) Or(spec Specification) Specification { + a := &OrSpecification{ + cs.Specification, spec, + } + a.Relate(a) + return a +} + +// 规格非操作 +func (cs *CompositeSpecification) Not() Specification { + a := &NotSpecification{ + cs.Specification, + } + a.Relate(a) + return a +} + +// 与规格有关 +func (cs *CompositeSpecification) Relate(spec Specification) { + cs.Specification = spec +} + +// 与规格 +type AndSpecification struct { + Specification + compare Specification +} + +// 检查规格 +func (as *AndSpecification) IsSatisfiedBy(in Invoice) bool { + return as.Specification.IsSatisfiedBy(in) && as.compare.IsSatisfiedBy(in) +} + +// 或规格 +type OrSpecification struct { + Specification + compare Specification +} + +// 检查规格 +func (os *OrSpecification) IsSatisfiedBy(in Invoice) bool { + return os.Specification.IsSatisfiedBy(in) || os.compare.IsSatisfiedBy(in) +} + +// 非规格 +type NotSpecification struct { + Specification +} + +// 检查规格 +func (ns *NotSpecification) IsSatisfiedBy(in Invoice) bool { + return ns.Specification.IsSatisfiedBy(in) +} + +// 数据到期规格 +type OverDueSpecification struct { + Specification +} + +// 检查规格 +func (os *OverDueSpecification) IsSatisfiedBy(in Invoice) bool { + return in.Day >= 30 +} + +// 创建数据到期规格 +func NewOverDueSpecification() Specification { + a := &OverDueSpecification{&CompositeSpecification{}} + a.Relate(a) + return a +} + +// 通知发送规格 +type NoticeSentSpecification struct { + Specification +} + +// 检查规格 +func (ns *NoticeSentSpecification) IsSatisfiedBy(in Invoice) bool { + return in.Notice >= 3 +} + +// 创建通知发送规格 +func NewNoticeSentSpecification() Specification { + a := &NoticeSentSpecification{&CompositeSpecification{}} + a.Relate(a) + return a +} + +// 是否收到发票通知规格 +type InCollectionSpecification struct { + Specification +} + +// 检查规格 +func (ics *InCollectionSpecification) IsSatisfiedBy(in Invoice) bool { + return !in.IsSent +} + +// 创建是否收到发票通知规格 +func NewInCollectionSpecification() Specification { + a := &InCollectionSpecification{&CompositeSpecification{}} + a.Relate(a) + return a +} diff --git a/chapter5/specification/example/specification.go b/chapter5/specification/example/specification.go new file mode 100644 index 0000000..00c152f --- /dev/null +++ b/chapter5/specification/example/specification.go @@ -0,0 +1,117 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package example + +// 对象 +type Object struct { + Attribute int +} + +// 规格接口 +type Specification interface { + IsSatisfiedBy(Object) bool + And(Specification) Specification + Or(Specification) Specification + Not() Specification + Relate(Specification) +} + +// 组合规格 +type CompositeSpecification struct { + Specification +} + +// 检查规格 +func (cs *CompositeSpecification) IsSatisfiedBy(obj Object) bool { + return false +} + +// 规格与操作 +func (cs *CompositeSpecification) And(spec Specification) Specification { + a := &AndSpecification{ + cs.Specification, spec, + } + a.Relate(a) + return a +} + +// 规格或操作 +func (cs *CompositeSpecification) Or(spec Specification) Specification { + a := &OrSpecification{ + cs.Specification, spec, + } + a.Relate(a) + return a +} + +// 规格非操作 +func (cs *CompositeSpecification) Not() Specification { + a := &NotSpecification{ + cs.Specification, + } + a.Relate(a) + return a +} + +// 与规格有关 +func (cs *CompositeSpecification) Relate(spec Specification) { + cs.Specification = spec +} + +// 与规格 +type AndSpecification struct { + Specification + compare Specification +} + +// 检查规格 +func (as *AndSpecification) IsSatisfiedBy(obj Object) bool { + return as.Specification.IsSatisfiedBy(obj) && as.compare.IsSatisfiedBy(obj) +} + +// 或规格 +type OrSpecification struct { + Specification + compare Specification +} + +// 检查规格 +func (os *OrSpecification) IsSatisfiedBy(obj Object) bool { + return os.Specification.IsSatisfiedBy(obj) || os.compare.IsSatisfiedBy(obj) +} + +// 非规格 +type NotSpecification struct { + Specification +} + +// 检查规格 +func (ns *NotSpecification) IsSatisfiedBy(obj Object) bool { + return ns.Specification.IsSatisfiedBy(obj) +} + +// 业务规格 +type BusinessSpecification struct { + Specification +} + +// 检查规格 +func (bs *BusinessSpecification) IsSatisfiedBy(obj Object) bool { + return obj.Attribute >= 8 +} + +// 构造函数 +func NewBusinessSpecification() Specification { + a := &BusinessSpecification{&CompositeSpecification{}} + a.Relate(a) + return a +} diff --git a/chapter5/specification/main-actual-combat.go b/chapter5/specification/main-actual-combat.go new file mode 100644 index 0000000..9900a53 --- /dev/null +++ b/chapter5/specification/main-actual-combat.go @@ -0,0 +1,41 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter6/specification/actualCombat" +) + +func main() { + //声明发票数据到期规格 + overDue := actualCombat.NewOverDueSpecification() + //声明发票通知发送规格 + noticeSent := actualCombat.NewNoticeSentSpecification() + //收款机构是否收到发票通知 + inCollection := actualCombat.NewInCollectionSpecification() + + sendToCollection := overDue.And(noticeSent).And(inCollection.Not()) + + object := actualCombat.Invoice{ + Day: 32, // >= 30 + Notice: 6, // >= 3 + IsSent: false, // false + } + + // 检查规格 + result := sendToCollection.IsSatisfiedBy(object) + fmt.Println(result) +} + +//$ go run main.go +//true diff --git a/chapter5/specification/main.go b/chapter5/specification/main.go new file mode 100644 index 0000000..f930b47 --- /dev/null +++ b/chapter5/specification/main.go @@ -0,0 +1,37 @@ +//++++++++++++++++++++++++++++++++++++++++ +// 《Go语言设计模式》源码 +//++++++++++++++++++++++++++++++++++++++++ +// Author:廖显东(ShirDon) +// Blog:https://www.shirdon.com/ +// 作者知乎:https://www.zhihu.com/people/shirdonl +// 仓库地址:https://gitee.com/shirdonl/goDesignPattern +// 仓库地址:https://github.com/shirdonl/goDesignPattern +// 交流咨询,请关注公众号"源码大数据" +//++++++++++++++++++++++++++++++++++++++++ + +package main + +import ( + "fmt" + "github.com/shirdonl/goDesignPattern/chapter6/specification/example" +) + +func main() { + //声明业务规格对象1 + biz1 := example.NewBusinessSpecification() + //声明业务规格对象2 + biz2 := example.NewBusinessSpecification() + + andResult := biz1.And(biz2) + + object := example.Object{ + Attribute: 8, + } + + // 检查规格 + result := andResult.IsSatisfiedBy(object) + fmt.Println(result) +} + +//$ go run main.go +//true