├── proxy ├── proxy_test.go ├── readfile │ └── readfile.go ├── example_test.go └── proxy.go ├── command ├── command_test.go ├── example_test.go └── command.go ├── observer ├── observer_test.go ├── example_test.go └── observer.go ├── template ├── template_test.go ├── example_test.go └── template.go ├── memento ├── game.bak ├── example_test.go └── memento.go ├── .gitignore ├── adapter ├── plug │ ├── iplug.go │ ├── twoplug.go │ ├── threeplug │ │ └── threeplug.go │ └── threeplug.go ├── adapter_test.go └── adapter.go ├── go.mod ├── single ├── single1_test.go ├── single2.go └── single1.go ├── Makefile ├── .travis.yml ├── abstractfactory ├── example_test.go └── abstractfactory.go ├── simplefactory ├── example_test.go └── simplefactory.go ├── flyweight ├── example_test.go ├── flyweight_test.go └── flyweight.go ├── prototype ├── example_test.go └── prototype.go ├── strategy ├── strate │ ├── strategy.go │ ├── discount.go │ └── fullsub.go ├── compute_test.go └── compute.go ├── state ├── example_test.go └── state.go ├── facade ├── example_test.go └── facade.go ├── iterator ├── example_test.go └── iterator.go ├── mediator ├── example_test.go └── mediator.go ├── chain ├── example_test.go └── chain.go ├── factorymethod ├── example_test.go └── factorymethod.go ├── options ├── options_test.go └── options.go ├── bridge ├── example_test.go └── bridge.go ├── visitor ├── example_test.go └── visitor.go ├── go.sum ├── decorator ├── example_test.go └── decorator.go ├── interperter ├── example_test.go └── interperter.go ├── composite ├── example_test.go └── composite.go ├── README.md └── LICENSE /proxy/proxy_test.go: -------------------------------------------------------------------------------- 1 | package proxy 2 | -------------------------------------------------------------------------------- /command/command_test.go: -------------------------------------------------------------------------------- 1 | package command 2 | -------------------------------------------------------------------------------- /observer/observer_test.go: -------------------------------------------------------------------------------- 1 | package observer 2 | -------------------------------------------------------------------------------- /template/template_test.go: -------------------------------------------------------------------------------- 1 | package template 2 | -------------------------------------------------------------------------------- /memento/game.bak: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaomeng79/go-design-pattern/HEAD/memento/game.bak -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #bench gen 2 | */*.test 3 | */*.profile 4 | */*.out 5 | */intarray.txt 6 | */*.svg 7 | .idea -------------------------------------------------------------------------------- /adapter/plug/iplug.go: -------------------------------------------------------------------------------- 1 | package plug 2 | 3 | //2孔插头接口 4 | type IPlug interface { 5 | Charge() 6 | } 7 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/xiaomeng79/go-design-pattern 2 | 3 | require ( 4 | github.com/davecgh/go-spew v1.1.1 // indirect 5 | github.com/pmezard/go-difflib v1.0.0 // indirect 6 | github.com/stretchr/testify v1.2.2 7 | ) 8 | -------------------------------------------------------------------------------- /single/single1_test.go: -------------------------------------------------------------------------------- 1 | package single 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestNew(t *testing.T) { 9 | assert.Exactly(t, New(), New(), "no equal") 10 | } 11 | -------------------------------------------------------------------------------- /adapter/plug/twoplug.go: -------------------------------------------------------------------------------- 1 | package plug 2 | 3 | import "fmt" 4 | 5 | //2孔插头 6 | type TwoPlug struct { 7 | } 8 | 9 | //充电方法,实现充电接口 10 | func (this TwoPlug) Charge() { 11 | fmt.Println("我是2孔插头,我使用方法:Charge充电") 12 | } 13 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | 3 | .PHONY : build 4 | build : fmt test 5 | @echo "可以提交" 6 | 7 | .PHONY : fmt 8 | fmt : 9 | @echo "格式化代码" 10 | @gofmt -l -w ./ 11 | 12 | 13 | 14 | .PHONY : test 15 | test : 16 | @echo "测试代码" 17 | @go test -v ./... -------------------------------------------------------------------------------- /proxy/readfile/readfile.go: -------------------------------------------------------------------------------- 1 | package readfile 2 | 3 | type IReadFile interface { 4 | ReadFile(string) string 5 | } 6 | 7 | type ReadFile struct { 8 | } 9 | 10 | func (r ReadFile) ReadFile(filename string) string { 11 | return "文件内容为:保密内容" 12 | } 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: go 3 | 4 | go: 5 | - "1.11.x" 6 | 7 | before_install: 8 | - go get github.com/stretchr/testify 9 | #- if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi 10 | 11 | script: 12 | make; -------------------------------------------------------------------------------- /adapter/plug/threeplug/threeplug.go: -------------------------------------------------------------------------------- 1 | package threeplug 2 | 3 | import "fmt" 4 | 5 | //3孔插头,未实现2孔插头 6 | 7 | type ThreePlug struct { 8 | } 9 | 10 | //充电方法,未实现充电接口 11 | func (this ThreePlug) ThreePlugCharge() { 12 | fmt.Println("我是3孔插头,我使用方法:ThreePlugCharge充电") 13 | } 14 | -------------------------------------------------------------------------------- /abstractfactory/example_test.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | func ExampleDellFactory_CreateMouse() { 4 | df := new(DellFactory) 5 | df.CreateMouse() 6 | df.CreateKeybo() 7 | df.Mouse.SayMouseBrand() 8 | df.Keybo.SayKeyBoBrand() 9 | //OutPut: 10 | //Hp Mouse 11 | //Dell Keybo 12 | } 13 | -------------------------------------------------------------------------------- /simplefactory/example_test.go: -------------------------------------------------------------------------------- 1 | package simplefactory 2 | 3 | func ExampleMouseFactory_CreateMouse() { 4 | var mf MouseFactory 5 | m := mf.CreateMouse(0) //戴尔鼠标 6 | m.SayMouseBrand() 7 | m = mf.CreateMouse(1) //惠普鼠标 8 | m.SayMouseBrand() 9 | //OutPut: 10 | //Dell Mouse 11 | //Hp Mouse 12 | 13 | } 14 | -------------------------------------------------------------------------------- /flyweight/example_test.go: -------------------------------------------------------------------------------- 1 | package flyweight 2 | 3 | import "fmt" 4 | 5 | func ExampleMysqlConnect_Do() { 6 | //初始化连接池 7 | mysqlpool := NewMysqlConnPool(2) 8 | //获取一个连接 9 | conn := mysqlpool.Get() 10 | //执行操作 11 | fmt.Println(conn.Do()) 12 | //放入连接池 13 | mysqlpool.Put(conn) 14 | //OutPut: 15 | //done 16 | } 17 | -------------------------------------------------------------------------------- /prototype/example_test.go: -------------------------------------------------------------------------------- 1 | package prototype 2 | 3 | func ExamplePeople_Clone() { 4 | //先实例化一个对象 5 | p := new(People) 6 | p.SetName("小明") 7 | p.Eat() 8 | //克隆一个对象小红 9 | p1 := p.Clone() 10 | p1.SetName("小红") 11 | p1.Eat() 12 | p1.Sleep() 13 | //OutPut: 14 | //小明 在吃饭 15 | //小红 在吃饭 16 | //小红 在睡觉 17 | 18 | } 19 | -------------------------------------------------------------------------------- /strategy/strate/strategy.go: -------------------------------------------------------------------------------- 1 | //装饰器模式 2 | package strate 3 | 4 | //意图:定义一系列的算法,实现同一个接口,把它们一个个封装起来, 并且使它们可相互替换 5 | //解决:算法相似的情况下,任意替换 6 | 7 | //实例:超市商品促销,有8折,7折,满200减10的 ,满500减100活动 8 | //定义2种策略,一种是折扣的策略,一种是满减的策略 9 | 10 | //定义接口,实现了策略接口 11 | 12 | type IStrategy interface { 13 | Compute() float64 //计算促销后的价格 14 | } 15 | -------------------------------------------------------------------------------- /adapter/adapter_test.go: -------------------------------------------------------------------------------- 1 | package adapter 2 | 3 | import "github.com/xiaomeng79/go-design-pattern/adapter/plug" 4 | 5 | func ExampleToCharge() { 6 | c1 := plug.TwoPlug{} 7 | c2 := plug.ThreePlugAdapter{} 8 | ToCharge(c1) 9 | ToCharge(c2) 10 | //OutPut: 11 | //我是2孔插头,我使用方法:Charge充电 12 | //我是3孔插头,我使用方法:ThreePlugCharge充电 13 | } 14 | -------------------------------------------------------------------------------- /state/example_test.go: -------------------------------------------------------------------------------- 1 | package state 2 | 3 | func ExampleLight_PressSwitch() { 4 | //初始化灯的状态:开灯状态 5 | light := &Light{State: &OpenLightState{}} 6 | //按下开关,每次按下开关,改变状态 7 | light.PressSwitch() 8 | light.PressSwitch() 9 | light.PressSwitch() 10 | 11 | //OutPut: 12 | //open light 13 | //close light 14 | //open light 15 | } 16 | -------------------------------------------------------------------------------- /proxy/example_test.go: -------------------------------------------------------------------------------- 1 | package proxy 2 | 3 | import "fmt" 4 | 5 | func ExampleReadFileProxy_ReadFileContext() { 6 | proxy := ReadFileProxy{} 7 | c1 := proxy.ReadFileContext("boy", "hello") 8 | c2 := proxy.ReadFileContext("boos", "hello") 9 | fmt.Println(c1) 10 | fmt.Println(c2) 11 | //OutPut: 12 | //无权查看 13 | //文件内容为:保密内容 14 | } 15 | -------------------------------------------------------------------------------- /strategy/strate/discount.go: -------------------------------------------------------------------------------- 1 | package strate 2 | 3 | //折扣 4 | 5 | type Discount struct { 6 | OriginalPrice float64 //原价 7 | Discount float64 //折扣 8 | } 9 | 10 | //计算 11 | func (d *Discount) Compute() float64 { 12 | if d.Discount <= 0 { 13 | return d.OriginalPrice 14 | } 15 | return d.OriginalPrice * d.Discount / 10 16 | } 17 | -------------------------------------------------------------------------------- /facade/example_test.go: -------------------------------------------------------------------------------- 1 | package facade 2 | 3 | func ExampleComputer_StartUp() { 4 | c := NewComputer() 5 | c.StartUp() 6 | //OutPut: 7 | //cpu startup 8 | //memory startup 9 | } 10 | 11 | func ExampleComputer_ShutDown() { 12 | c := NewComputer() 13 | c.ShutDown() 14 | //OutPut: 15 | //cpu shutdown 16 | //membory shutdown 17 | 18 | } 19 | -------------------------------------------------------------------------------- /iterator/example_test.go: -------------------------------------------------------------------------------- 1 | package iterator 2 | 3 | func ExamplePeoplesIterator_Iterator() { 4 | p1 := &Person{"小明01", 16, "足球"} 5 | p2 := &Person{"小明02", 17, "篮球,足球"} 6 | ps := &Peoples{} 7 | ps.Add(p1, p2) 8 | pi := ps.CreateIterator() 9 | pi.Iterator() 10 | //OutPut: 11 | //姓名:小明01,年龄:16,爱好:足球 12 | //姓名:小明02,年龄:17,爱好:篮球,足球 13 | 14 | } 15 | -------------------------------------------------------------------------------- /mediator/example_test.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | func ExampleUser_SendMessage() { 4 | //先实例化一个聊天室 5 | c := &ChatRoom1{} 6 | //实例化2个用户 7 | u1 := &User{Id: 1} 8 | u2 := &User{Id: 2} 9 | //加入聊天室 10 | u1.Join(c) 11 | u2.Join(c) 12 | //发送消息 13 | u1.SendMessage("大家好") 14 | //OutPut: 15 | //发送给用户:1,消息为:大家好 16 | //发送给用户:2,消息为:大家好 17 | } 18 | -------------------------------------------------------------------------------- /chain/example_test.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | func ExampleManagerHandler_ProcessRequest() { 4 | //新建一个采购请求,4999在副总经理审批的范围 5 | req := &PurchaseRequest{Amount: 4999.00} 6 | //建立处理链 7 | h := &ManagerHandler{Successor: &ViceGeneralManagerHandler{Successor: &GeneralManagerHandler{}}} 8 | h.ProcessRequest(req) 9 | //OutPut: 10 | //我是副总经理,我可以处理! 11 | } 12 | -------------------------------------------------------------------------------- /adapter/plug/threeplug.go: -------------------------------------------------------------------------------- 1 | package plug 2 | 3 | import "github.com/xiaomeng79/go-design-pattern/adapter/plug/threeplug" 4 | 5 | //通过适配器,在不改变3孔充电方法的情况下,将3孔充电适配2孔充电方法的接口 6 | 7 | type ThreePlugAdapter struct { 8 | threeplug.ThreePlug 9 | } 10 | 11 | //实现充电接口,不需要关心2孔插头内部的实现 12 | func (this ThreePlugAdapter) Charge() { 13 | this.ThreePlug.ThreePlugCharge() 14 | } 15 | -------------------------------------------------------------------------------- /single/single2.go: -------------------------------------------------------------------------------- 1 | //单例模式2 2 | package single 3 | 4 | //意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点 5 | //解决:一个全局使用的类频繁地创建与销毁 6 | 7 | //实例:利用go的init 实现一个单例模式 8 | 9 | import "net/http" 10 | 11 | var ( 12 | instance2 *http.Client 13 | ) 14 | 15 | func init() { 16 | instance2 = &http.Client{ 17 | Timeout: 30, //超时30s 18 | Transport: http.DefaultTransport, 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /strategy/strate/fullsub.go: -------------------------------------------------------------------------------- 1 | package strate 2 | 3 | //满减 4 | type FullSub struct { 5 | OriginalPrice float64 //原价 6 | Full float64 //满 7 | Sub float64 //减 8 | } 9 | 10 | //计算 11 | func (f *FullSub) Compute() float64 { 12 | //原价小于要进行满减的要求 13 | if f.OriginalPrice < f.Full { 14 | return f.OriginalPrice 15 | } 16 | return f.OriginalPrice - f.Sub 17 | } 18 | -------------------------------------------------------------------------------- /factorymethod/example_test.go: -------------------------------------------------------------------------------- 1 | package factorymethod 2 | 3 | func ExampleDellMouseFactory_Create() { 4 | var dmf DellMouseFactory 5 | dm := dmf.Create() 6 | dm.SayMouseBrand() 7 | //OutPut: 8 | //Dell Mouse 9 | } 10 | 11 | func ExampleHpMouseFactory_Create() { 12 | var hmf HpMouseFactory 13 | hm := hmf.Create() 14 | hm.SayMouseBrand() 15 | //OutPut: 16 | //Hp Mouse 17 | } 18 | -------------------------------------------------------------------------------- /observer/example_test.go: -------------------------------------------------------------------------------- 1 | package observer 2 | 3 | func ExampleTest() { 4 | ob1 := &eventObserver{id: 1} 5 | ob2 := &eventObserver{id: 2} 6 | //通知者 7 | o := eventNotifier{observers: make(map[Observer]struct{}, 2)} 8 | //注册 9 | o.Register(ob1) 10 | o.Register(ob2) 11 | //发送 12 | o.Notify(Event{Data: 222}) 13 | //OutPut: 14 | //*** Observer 1 received:222 15 | //*** Observer 2 received:222 16 | } 17 | -------------------------------------------------------------------------------- /options/options_test.go: -------------------------------------------------------------------------------- 1 | package options 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "log" 6 | "testing" 7 | ) 8 | 9 | func TestNewLog(t *testing.T) { 10 | //新建一个日志,并修改默认选项 11 | l := NewLog( 12 | WithPrefix("noprefix"), 13 | ) 14 | assert.Equal(t, "noprefix", l.Prefix(), "prefix not equal") 15 | //flag 使用默认值 16 | assert.Equal(t, log.Ltime, l.Flags(), "flag not equal") 17 | } 18 | -------------------------------------------------------------------------------- /bridge/example_test.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | func ExampleCommonMessage_SendMessage() { 4 | m := NewCommonMessage(ViaSMS()) 5 | m.SendMessage("have a drink?", "bob") 6 | //OutPut: 7 | //send have a drink? to bob via SMS 8 | } 9 | 10 | func ExampleUrgencySMS() { 11 | m := NewUrgencyMessage(ViaSMS()) 12 | m.SendMessage("have a drink?", "bob") 13 | // Output: 14 | // send [Urgency] have a drink? to bob via SMS 15 | } 16 | -------------------------------------------------------------------------------- /template/example_test.go: -------------------------------------------------------------------------------- 1 | package template 2 | 3 | func ExampleMan_Dress() { 4 | m := Man{p: &Person{}} 5 | m.SetSex() //自定义的方法 6 | m.p.Eat("米饭") //使用模板中的方法 7 | m.Dress() //自定义的方法 8 | //OutPut: 9 | //吃食物 米饭 10 | //男人 化妆, 刮胡子 11 | } 12 | 13 | func ExampleWomen_Dress() { 14 | w := Women{p: &Person{}} 15 | w.SetSex() //自定义的方法 16 | w.p.Eat("麻辣烫") //使用模板中的方法 17 | w.Dress() //自定义的方法 18 | //OutPut: 19 | //吃食物 麻辣烫 20 | //女人 化妆, 涂口红 21 | 22 | } 23 | -------------------------------------------------------------------------------- /visitor/example_test.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | func ExampleObjectStructure_Accept() { 4 | object := ObjectStructure{} 5 | object.Attach(&ConcreteElementA{"A"}) 6 | object.Attach(&ConcreteElementB{"B"}) 7 | 8 | cva := ConcreteVisitorA{"vA"} 9 | cvb := ConcreteVisitorB{"vB"} 10 | 11 | object.Accept(&cva) 12 | object.Accept(&cvb) 13 | 14 | //OutPut: 15 | //A vA 16 | //OperatorA 17 | //B vA 18 | //OperatorB 19 | //A vB 20 | //OperatorA 21 | //B vB 22 | //OperatorB 23 | 24 | } 25 | -------------------------------------------------------------------------------- /flyweight/flyweight_test.go: -------------------------------------------------------------------------------- 1 | package flyweight 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | //mysql连接数不足的时候,是否新建 9 | func TestNewMysqlConnPool(t *testing.T) { 10 | //新建只有一个的连接池 11 | mysqlpool := NewMysqlConnPool(1) 12 | //获取一个连接,执行完未放入连接池 13 | conn1 := mysqlpool.Get() 14 | //又要获取一个连接 15 | conn2 := mysqlpool.Get() 16 | //执行 17 | str := conn2.Do() 18 | mysqlpool.Put(conn1) 19 | mysqlpool.Put(conn2) 20 | assert.Equal(t, "done", str, "fail") 21 | 22 | } 23 | -------------------------------------------------------------------------------- /adapter/adapter.go: -------------------------------------------------------------------------------- 1 | //适配器模式 2 | package adapter 3 | 4 | import "github.com/xiaomeng79/go-design-pattern/adapter/plug" 5 | 6 | //意图:使得原本由于接口不兼容而不能一起工作的那些类可以一起工作 7 | //解决:主要解决在软件系统中,常常要将一些"现存的对象"放到新的环境中,而新环境要求的接口是现对象不能满足的 8 | 9 | //实例:电源有2孔插头,3孔插头,现在只有2孔的插排,需要一个适配器将3孔的插头转化成2孔的插头 10 | 11 | //实现实例 12 | //c := plug.TwoPlug{}//使用2孔插头充电 13 | //c := plug.ThreePlugAdapter{} //使用3孔插头充电 14 | //虽然3孔插头没实现充电接口,但是3孔插头的适配器实现了充电接口,所有都可以使用ToCharge方法 15 | 16 | //使用插头充电 17 | func ToCharge(c plug.IPlug) { 18 | c.Charge() 19 | } 20 | -------------------------------------------------------------------------------- /memento/example_test.go: -------------------------------------------------------------------------------- 1 | package memento 2 | 3 | func ExampleGame_Play() { 4 | //初始化游戏 5 | g := GameInit() 6 | //查看游戏状态 7 | g.Status() 8 | //玩游戏 9 | g.Play(5, 5) 10 | //查看游戏状态 11 | g.Status() 12 | //存档 13 | gm := &GameMemento{} 14 | gm.Save(g) 15 | //初始化游戏 16 | g = GameInit() 17 | //查看游戏状态 18 | g.Status() 19 | //恢复 20 | g = gm.Load() 21 | //查看游戏状态 22 | g.Status() 23 | 24 | //OutPut: 25 | //Current HP:0, MP:0 26 | //Current HP:5, MP:5 27 | //Current HP:0, MP:0 28 | //Current HP:5, MP:5 29 | 30 | } 31 | -------------------------------------------------------------------------------- /single/single1.go: -------------------------------------------------------------------------------- 1 | //单例模式 2 | 3 | package single 4 | 5 | //意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点 6 | //解决:一个全局使用的类频繁地创建与销毁 7 | 8 | //实例:利用go包sync 和 首字母小写对外不可见 实现一个单例模式 9 | 10 | import ( 11 | "net/http" 12 | "sync" 13 | ) 14 | 15 | //实现一个全局唯一的http客户端 16 | var ( 17 | once sync.Once 18 | instance *http.Client 19 | ) 20 | 21 | func New() *http.Client { 22 | once.Do(func() { 23 | instance = &http.Client{ 24 | Timeout: 30, //超时30s 25 | Transport: http.DefaultTransport, 26 | } 27 | }) 28 | return instance 29 | } 30 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 6 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 7 | -------------------------------------------------------------------------------- /decorator/example_test.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | import "fmt" 4 | 5 | func ExampleBottleMilk_Desc() { 6 | p := &Packing{name: "普通蛋糕", price: 10.00} //普通蛋糕10元 7 | gp := &GlassPack{pack: p, name: "外加玻璃套", price: 2.00} //加一个玻璃盒子包装加2元 8 | pgp := &PlasticPack{pack: gp, name: "外加塑料套", price: 1.00} //加一个塑料盒子包装加1元 9 | gpgp := &GlassPack{pack: pgp, name: "外加玻璃套", price: 2.00} //加一个玻璃盒子包装加2元 10 | 11 | fmt.Printf("名称:%s,价格:%f\n", gpgp.Desc(), gpgp.Price()) 12 | //Output: 13 | //名称:普通蛋糕外加玻璃套外加塑料套外加玻璃套,价格:15.000000 14 | } 15 | -------------------------------------------------------------------------------- /interperter/example_test.go: -------------------------------------------------------------------------------- 1 | package interperter 2 | 3 | import "fmt" 4 | 5 | func ExampleTerminalExpression_Interpret() { 6 | isMale := &OrExpression{&TerminalExpression{"Robert"}, &TerminalExpression{"John"}} 7 | fmt.Println("John is male?", isMale.Interpret("John")) 8 | isMarriedWoman := &AndExpression{&TerminalExpression{"Julie"}, &TerminalExpression{"Married"}} 9 | fmt.Println("Julie is a married women?", isMarriedWoman.Interpret("Married Julie")) 10 | //OutPut: 11 | //John is male? true 12 | //Julie is a married women? true 13 | } 14 | -------------------------------------------------------------------------------- /command/example_test.go: -------------------------------------------------------------------------------- 1 | package command 2 | 3 | func ExampleInvoker_Do() { 4 | //电视实例 5 | tv := &TV{Name: "熊猫"} 6 | //实例化打开命令 7 | opencmd := OpenCommand{Tv: tv} 8 | //执行打开命令 9 | invoker := Invoker{cmd: opencmd} 10 | invoker.Do() 11 | //实例化关闭命令 12 | closecmd := CloseCommand{Tv: tv} 13 | //执行关闭命令 14 | invoker.SetCommand(closecmd) 15 | invoker.Do() 16 | 17 | //更换电视实例 18 | tv = &TV{Name: "黑熊"} 19 | opencmd = OpenCommand{Tv: tv} 20 | invoker.SetCommand(opencmd) 21 | invoker.Do() 22 | 23 | //OutPut: 24 | //打开熊猫电视 25 | //关闭熊猫电视 26 | //打开黑熊电视 27 | } 28 | -------------------------------------------------------------------------------- /prototype/prototype.go: -------------------------------------------------------------------------------- 1 | //原型模式 2 | package prototype 3 | 4 | import "fmt" 5 | 6 | //意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象 7 | //解决:利用已有的一个原型对象,快速地生成和原型对象一样的实例 8 | 9 | //实例:人类有吃饭,睡觉方法,克隆一个人,使其拥有同样的方法 10 | 11 | type IPerson interface { 12 | Eat() 13 | Sleep() 14 | } 15 | 16 | type People struct { 17 | name string 18 | } 19 | 20 | func (p *People) SetName(name string) { 21 | p.name = name 22 | } 23 | 24 | func (p *People) Eat() { 25 | fmt.Println(p.name, "在吃饭") 26 | } 27 | 28 | func (p *People) Sleep() { 29 | fmt.Println(p.name, "在睡觉") 30 | } 31 | 32 | func (p *People) Clone() *People { 33 | if p == nil { 34 | return nil 35 | } 36 | new_obj := (*p) 37 | return &new_obj 38 | } 39 | -------------------------------------------------------------------------------- /strategy/compute_test.go: -------------------------------------------------------------------------------- 1 | package strategy 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestPriceCompute_Do(t *testing.T) { 9 | computeValues := []struct { 10 | price float64 11 | promotionType string 12 | result float64 13 | }{ 14 | {200, "满200减100", 100}, 15 | {150, "满200减100", 150}, 16 | {200.3583654875, "满200减 100.3235124545", 100.03}, 17 | {200.3593654875, "满200减 100.3235124545", 100.04}, 18 | {1, "满1减0.8", 0.20}, 19 | {200, "8折", 160}, 20 | {200, "8.8折", 176}, 21 | } 22 | 23 | for _, v := range computeValues { 24 | com := &PriceCompute{v.price, v.promotionType, nil} 25 | res := com.Do() 26 | assert.Exactly(t, v.result, res, "计算不正确") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /composite/example_test.go: -------------------------------------------------------------------------------- 1 | package composite 2 | 3 | func ExampleNewRealCompany() { 4 | //新建一个总公司 5 | root := NewRealCompany("华夏集团") 6 | //新建1个部门 7 | rs := NewDepartment("人事部") 8 | //添加到总公司 9 | root.Add(rs) 10 | //再建2个分公司 11 | c1 := NewRealCompany("华夏集团北京分公司") 12 | c2 := NewRealCompany("华夏集团上海分公司") 13 | //添加到总公司 14 | root.Add(c1) 15 | root.Add(c2) 16 | //为北京公司新建2个部门 17 | rs1 := NewDepartment("人事部") 18 | cw1 := NewDepartment("财务部") 19 | //加入到北京公司 20 | c1.Add(rs1) 21 | c1.Add(cw1) 22 | //为上海公司新建一个部门 23 | cw2 := NewDepartment("财务部") 24 | c2.Add(cw2) 25 | //打印集团结构树 26 | root.Display(0) 27 | //OutPut: 28 | //华夏集团 29 | //-- 人事部 30 | //-- 华夏集团北京分公司 31 | //---- 人事部 32 | //---- 财务部 33 | //-- 华夏集团上海分公司 34 | //---- 财务部 35 | 36 | } 37 | -------------------------------------------------------------------------------- /simplefactory/simplefactory.go: -------------------------------------------------------------------------------- 1 | //简单工厂模式,不是23种之一 2 | package simplefactory 3 | 4 | import "fmt" 5 | 6 | //意图:将对象的创建过程进行了封装,用户不需要知道具体的创建过程,只需要调用工厂类获取对象即可 7 | //解决:创建过程的复杂性 8 | 9 | //不足:简单工厂的写法是通过switch-case来判断对象创建过程的。在实际使用过程中,违背了 开放-关闭原则,当然有些情况下可以通过反射调用来弥补这种不足。 10 | 11 | //实例:实现一个生产鼠标工厂的类,通过输入参数不同,实例化不同品牌的鼠标工厂 12 | 13 | //鼠标接口 14 | type IMouse interface { 15 | SayMouseBrand() 16 | } 17 | 18 | //戴尔鼠标 19 | type DellMouse struct{} 20 | 21 | func (d DellMouse) SayMouseBrand() { 22 | fmt.Println("Dell Mouse") 23 | } 24 | 25 | //惠普鼠标 26 | type HpMouse struct{} 27 | 28 | func (h HpMouse) SayMouseBrand() { 29 | fmt.Println("Hp Mouse") 30 | } 31 | 32 | //实例化鼠标工厂 33 | type MouseFactory struct{} 34 | 35 | func (m MouseFactory) CreateMouse(i int) IMouse { 36 | switch i { 37 | case 0: //戴尔 38 | return new(DellMouse) 39 | case 1: //惠普 40 | return new(HpMouse) 41 | } 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /proxy/proxy.go: -------------------------------------------------------------------------------- 1 | //代理模式 2 | package proxy 3 | 4 | import "github.com/xiaomeng79/go-design-pattern/proxy/readfile" 5 | 6 | //意图:为其他对象提供一种代理以控制对这个对象的访问 7 | //解决:想在访问一个类时做一些[安全]控制或者直接访问对象很麻烦 8 | //注意事项: 9 | // 1、和适配器模式的区别:适配器模式主要改变所考虑对象的接口,而代理模式不能改变所代理类的接口。 10 | // 2、和装饰器模式的区别:装饰器模式为了增强功能,而代理模式是为了加以控制 11 | // 3. 和中介者模式的区别: 中介者模式为了减少对象之间的相互耦合 12 | 13 | //实例:有一个访问本地磁盘文件的接口,但是现在需要权限认证后才可以访问 14 | //实例2:也可以实现一个代理,可以读取本地文件,可以读取网络文件(未实现) 15 | 16 | type IReadFileProxy interface { 17 | ReadFileContext(string, string) string 18 | } 19 | 20 | type ReadFileProxy struct { 21 | } 22 | 23 | func (r ReadFileProxy) auth(name string) bool { 24 | if name == "boos" { 25 | return true 26 | } 27 | return false 28 | } 29 | 30 | func (r ReadFileProxy) ReadFileContext(name, filename string) string { 31 | if !r.auth(name) { 32 | return "无权查看" 33 | } 34 | //代理去调用读文件接口读取 35 | read := readfile.ReadFile{} 36 | return read.ReadFile(filename) 37 | } 38 | -------------------------------------------------------------------------------- /state/state.go: -------------------------------------------------------------------------------- 1 | //状态模式 2 | package state 3 | 4 | import "fmt" 5 | 6 | //意图:当对象的状态改变时,同时改变其行为 7 | //解决:对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为 8 | //使用场景: 1、行为随状态改变而改变的场景。 2、条件、分支语句的代替者 9 | 10 | //实例:灯开关,当灯的状态为关着的时候,按开关,灯就会开,反之... ,开关就是行为,当状态不一样的时候,行为也不同 11 | 12 | //灯 13 | type Light struct { 14 | State ILightState 15 | } 16 | 17 | //开关 18 | func (l *Light) PressSwitch() { 19 | if l.State != nil { 20 | l.State.PressSwitch(l) 21 | } 22 | } 23 | 24 | //灯状态接口 25 | type ILightState interface { 26 | PressSwitch(*Light) 27 | } 28 | 29 | //开灯 30 | type OpenLightState struct{} 31 | 32 | func (o *OpenLightState) PressSwitch(l *Light) { 33 | fmt.Println("open light") 34 | //改变灯的下一个状态为关灯 35 | l.State = &CloseLightState{} 36 | } 37 | 38 | //关灯 39 | type CloseLightState struct{} 40 | 41 | func (c *CloseLightState) PressSwitch(l *Light) { 42 | fmt.Println("close light") 43 | //改变灯的下一个状态为开灯 44 | l.State = &OpenLightState{} 45 | } 46 | -------------------------------------------------------------------------------- /factorymethod/factorymethod.go: -------------------------------------------------------------------------------- 1 | //工厂方法模式 2 | package factorymethod 3 | 4 | import "fmt" 5 | 6 | //意图:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行 7 | //解决:主要解决接口选择的问题 8 | 9 | //不足:选择判断问题还是存在的。也就是说,工厂方法把简单的工厂内部逻辑判断转移到了客户端来运行。 10 | 11 | //实例:实现一个鼠标工厂的实现的接口,不同品牌的鼠标工厂实现它 12 | 13 | //鼠标接口 14 | type IMouse interface { 15 | SayMouseBrand() 16 | } 17 | 18 | //戴尔鼠标 19 | type DellMouse struct{} 20 | 21 | func (d DellMouse) SayMouseBrand() { 22 | fmt.Println("Dell Mouse") 23 | } 24 | 25 | //惠普鼠标 26 | type HpMouse struct{} 27 | 28 | func (h HpMouse) SayMouseBrand() { 29 | fmt.Println("Hp Mouse") 30 | } 31 | 32 | //鼠标工厂接口 33 | type IMouseFactory interface { 34 | Create() IMouse 35 | } 36 | 37 | //戴尔鼠标工厂实现 38 | type DellMouseFactory struct{} 39 | 40 | func (d DellMouseFactory) Create() IMouse { 41 | return DellMouse{} 42 | } 43 | 44 | //惠普鼠标工厂 45 | type HpMouseFactory struct{} 46 | 47 | func (h HpMouseFactory) Create() IMouse { 48 | return HpMouse{} 49 | } 50 | -------------------------------------------------------------------------------- /options/options.go: -------------------------------------------------------------------------------- 1 | //选项模式 2 | package options 3 | 4 | //意图:通过修改选项,创建出功能不同的实例 5 | //解决:由于go语言没有默认值,继承,多态,所有使用选项模式来达到默认值,多态的效果 6 | 7 | //实例:配置一个日志 8 | 9 | import ( 10 | "io" 11 | "log" 12 | "os" 13 | ) 14 | 15 | type Option func(*Options) 16 | 17 | type Options struct { 18 | Out io.Writer //日志输出 19 | Prefix string //日志前缀 20 | Flag int //日志标记 21 | } 22 | 23 | //设置输出 24 | func WithOut(out io.Writer) Option { 25 | return func(o *Options) { 26 | o.Out = out 27 | } 28 | } 29 | 30 | //设置前缀 31 | func WithPrefix(prefix string) Option { 32 | return func(o *Options) { 33 | o.Prefix = prefix 34 | } 35 | } 36 | 37 | //设置标记 38 | func WithFlag(flag int) Option { 39 | return func(o *Options) { 40 | o.Flag = flag 41 | } 42 | } 43 | 44 | //新建一个日志 45 | func NewLog(opts ...Option) *log.Logger { 46 | //设置默认选项 47 | o := &Options{ 48 | Out: os.Stderr, 49 | Prefix: "", 50 | Flag: log.Ltime, 51 | } 52 | //使用自定义选项覆盖默认选项 53 | for _, opt := range opts { 54 | opt(o) 55 | } 56 | return log.New(o.Out, o.Prefix, o.Flag) 57 | } 58 | -------------------------------------------------------------------------------- /decorator/decorator.go: -------------------------------------------------------------------------------- 1 | //装饰器模式 2 | package decorator 3 | 4 | //意图:动态地给一个对象添加一些额外的职责,不改变对象的主要功能 5 | //解决:对现有的对象添加新的功能,同时又不改变其结构,现有类的包装 6 | 7 | //实例:对蛋糕进行包装,包装:普通包装,塑料包装 玻璃包装 8 | 9 | //包装 10 | type IPack interface { 11 | Desc() string 12 | Price() float32 13 | } 14 | 15 | //普通包装 16 | type Packing struct { 17 | name string 18 | price float32 19 | } 20 | 21 | func (p Packing) Desc() string { 22 | return p.name 23 | } 24 | 25 | func (p Packing) Price() float32 { 26 | return p.price 27 | } 28 | 29 | //塑料盒包装 30 | type PlasticPack struct { 31 | pack IPack 32 | name string 33 | price float32 34 | } 35 | 36 | func (p PlasticPack) Desc() string { 37 | return p.pack.Desc() + p.name 38 | } 39 | func (p PlasticPack) Price() float32 { 40 | return p.pack.Price() + p.price 41 | } 42 | 43 | //玻璃盒包装 44 | type GlassPack struct { 45 | pack IPack 46 | name string 47 | price float32 48 | } 49 | 50 | func (p GlassPack) Desc() string { 51 | return p.pack.Desc() + p.name 52 | } 53 | func (p GlassPack) Price() float32 { 54 | return p.pack.Price() + p.price 55 | } 56 | -------------------------------------------------------------------------------- /observer/observer.go: -------------------------------------------------------------------------------- 1 | //观察者模式 2 | package observer 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | //意图:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新 9 | //解决:一个对象状态改变给其他对象通知的问题,而且要考虑到易用和低耦合,保证高度的协作 10 | 11 | //实例:当程序接收到用户的信号的时候,通知其他监听的程序做响应处理 12 | 13 | type ( 14 | //事件 15 | Event struct { 16 | Data int64 17 | } 18 | //观察者 19 | Observer interface { 20 | OnNotify(Event) 21 | } 22 | //通知者 23 | Notifier interface { 24 | //注册 25 | Register(Observer) 26 | //取消注册 27 | Deregister(Observer) 28 | //通知 29 | Notify(Event) 30 | } 31 | ) 32 | 33 | type ( 34 | eventObserver struct { 35 | id int 36 | } 37 | eventNotifier struct { 38 | observers map[Observer]struct{} 39 | } 40 | ) 41 | 42 | func (o *eventObserver) OnNotify(e Event) { 43 | fmt.Printf("*** Observer %d received:%d\n", o.id, e.Data) 44 | } 45 | 46 | func (o *eventNotifier) Register(l Observer) { 47 | o.observers[l] = struct{}{} 48 | } 49 | 50 | func (o *eventNotifier) Deregister(l Observer) { 51 | delete(o.observers, l) 52 | } 53 | 54 | func (o *eventNotifier) Notify(e Event) { 55 | for l := range o.observers { 56 | l.OnNotify(e) 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /flyweight/flyweight.go: -------------------------------------------------------------------------------- 1 | //享元模式 2 | package flyweight 3 | 4 | //意图:享元模式从对象中剥离出不发生改变且多个实例需要的重复数据,独立出一个享元,使多个对象共享,从而节省内存以及减少对象数量 5 | //解决:在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建 6 | 7 | //实例:数据库的连接池 8 | 9 | //DB接口 10 | type IDBConnect interface { 11 | Do() string 12 | } 13 | 14 | //连接池接口 15 | type IDBPool interface { 16 | Get() IDBConnect 17 | Put(IDBConnect) 18 | } 19 | 20 | //数据库连接 21 | type MysqlConnect struct { 22 | } 23 | 24 | //数据库操作 25 | func (db *MysqlConnect) Do() string { 26 | return "done" 27 | } 28 | 29 | //连接池实例 mysql 30 | type MysqlConnPool struct { 31 | ConnChan chan *MysqlConnect 32 | } 33 | 34 | //初始化连接池 35 | func NewMysqlConnPool(num int) *MysqlConnPool { 36 | return &MysqlConnPool{ConnChan: make(chan *MysqlConnect, num)} 37 | } 38 | 39 | //获取连接 40 | func (p *MysqlConnPool) Get() IDBConnect { 41 | select { 42 | case conn := <-p.ConnChan: 43 | return conn 44 | default: 45 | return new(MysqlConnect) 46 | } 47 | } 48 | 49 | //存入连接 50 | func (p *MysqlConnPool) Put(conn IDBConnect) { 51 | select { 52 | case p.ConnChan <- conn.(*MysqlConnect): 53 | return 54 | default: 55 | //丢弃 56 | return 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /template/template.go: -------------------------------------------------------------------------------- 1 | //模板模式 2 | package template 3 | 4 | import "fmt" 5 | 6 | //意图:在一个抽象类中定义一个操作中的算法骨架(对应于生活中的大家下载的模板),而将一些步骤延迟到子类中去实现(对应于我们根据自己的情况向模板填充内容)。 7 | // 模板方法使得子类可以不改变一个算法的结构前提下,重新定义算法的某些特定步骤,模板方法模式把不变行为搬到超类中,从而去除了子类中的重复代码。 8 | 9 | //解决:一些通用的方法,在每个子类都写一遍,减少代码量和修改难度 10 | 11 | //优点:1.实现了代码复用 2.能够灵活应对子步骤的变化,符合开放-封闭原则 12 | 13 | //实例:人类有吃饭,睡觉,化妆的方法,男女人吃饭睡觉都相同,但化妆不同,我们只需要在男女类中重写化妆方法即可 14 | 15 | type IPerson interface { 16 | SetSex() 17 | Eat(string) 18 | Dress() 19 | } 20 | 21 | //人类 22 | type Person struct { 23 | sex string 24 | } 25 | 26 | func (p *Person) SetSex() { 27 | p.sex = "unknow" 28 | } 29 | 30 | func (p *Person) Eat(s string) { 31 | fmt.Println("吃食物 ", s) 32 | } 33 | 34 | func (p *Person) Dress() { 35 | fmt.Println("unknow") 36 | } 37 | 38 | //男人 39 | 40 | type Man struct { 41 | p *Person 42 | } 43 | 44 | func (m Man) SetSex() { 45 | m.p.sex = "男人" 46 | } 47 | 48 | //重写化妆 49 | func (m Man) Dress() { 50 | fmt.Println(m.p.sex, "化妆, ", "刮胡子") 51 | } 52 | 53 | //女人 54 | type Women struct { 55 | p *Person 56 | } 57 | 58 | func (w Women) SetSex() { 59 | w.p.sex = "女人" 60 | } 61 | 62 | //重写化妆 63 | func (w Women) Dress() { 64 | fmt.Println(w.p.sex, "化妆, ", "涂口红") 65 | } 66 | -------------------------------------------------------------------------------- /mediator/mediator.go: -------------------------------------------------------------------------------- 1 | //中介者模式 2 | package mediator 3 | 4 | import "fmt" 5 | 6 | //意图:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互 7 | //解决:对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理,由网状结构变为星状结构 8 | //使用场景: 1、系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象。 2、想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类 9 | 10 | //实例:一群用户之间信息交流,可以通过建立一个聊天室来进行,而不是每个用户和一群用户之间通讯,其中的聊天室就是中介者,如果一个用户向聊天室(中介者)发消息,聊天室就广播所有人消息 11 | 12 | //聊天室 13 | type IChatRoom interface { 14 | SendAllUserMessage(string) //向所有用户发送消息 15 | JoinUsers(...int) 16 | } 17 | 18 | //用户 19 | type IUser interface { 20 | Join(IChatRoom) //加入聊天室 21 | SendMessage(string) //发送消息 22 | } 23 | 24 | //聊天室 25 | type ChatRoom1 struct { 26 | userIds []int 27 | } 28 | 29 | func (c *ChatRoom1) SendAllUserMessage(msg string) { 30 | for _, v := range c.userIds { 31 | fmt.Printf("发送给用户:%d,消息为:%s\n", v, msg) 32 | } 33 | } 34 | func (c *ChatRoom1) JoinUsers(uid ...int) { 35 | c.userIds = append(c.userIds, uid...) 36 | } 37 | 38 | //用户 39 | type User struct { 40 | Id int 41 | c IChatRoom 42 | } 43 | 44 | func (u *User) Join(c IChatRoom) { 45 | c.JoinUsers(u.Id) 46 | u.c = c 47 | } 48 | func (u *User) SendMessage(msg string) { 49 | u.c.SendAllUserMessage(msg) 50 | } 51 | -------------------------------------------------------------------------------- /command/command.go: -------------------------------------------------------------------------------- 1 | //命令模式 2 | package command 3 | 4 | import "fmt" 5 | 6 | //意图:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化 7 | //解决: 在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系 8 | 9 | //实例:人使用遥控器按下开机键打开电视的过程,人就是客户端,电视遥控器就是调用者,按键就是具体的调用的命令,电视就是接收执行命令者 10 | 11 | //心得: 此实例中,电视为行为实现者,可以随时更换,而不影响行为请求者 12 | 13 | type ICommand interface { 14 | Press() //按键操作,执行命令 15 | } 16 | 17 | //按键 18 | //开机命令 19 | type OpenCommand struct { 20 | Tv ITV 21 | } 22 | 23 | func (o OpenCommand) Press() { 24 | o.Tv.Open() 25 | } 26 | 27 | //关机命令 28 | type CloseCommand struct { 29 | Tv ITV 30 | } 31 | 32 | func (c CloseCommand) Press() { 33 | c.Tv.Close() 34 | } 35 | 36 | //电视 37 | type ITV interface { 38 | Open() 39 | Close() 40 | } 41 | type TV struct { 42 | Name string //电视名称 43 | } 44 | 45 | func (t *TV) Open() { 46 | fmt.Println("打开" + t.Name + "电视") 47 | } 48 | 49 | func (t *TV) Close() { 50 | fmt.Println("关闭" + t.Name + "电视") 51 | } 52 | 53 | //遥控器 54 | //按键按下就是设置命令,松开就是执行命令 55 | type IInvoker interface { 56 | SetCommand(ICommand) //设置命令 57 | Do() //执行命令 58 | } 59 | 60 | type Invoker struct { 61 | cmd ICommand 62 | } 63 | 64 | func (i *Invoker) SetCommand(command ICommand) { 65 | i.cmd = command 66 | } 67 | 68 | func (i *Invoker) Do() { 69 | i.cmd.Press() 70 | } 71 | -------------------------------------------------------------------------------- /memento/memento.go: -------------------------------------------------------------------------------- 1 | //备忘录模式 2 | package memento 3 | 4 | import ( 5 | "encoding/gob" 6 | "fmt" 7 | "os" 8 | ) 9 | 10 | //意图:保存程序内部状态到外部,又不希望暴露内部状态的情形,可以离线保存内部状态,如保存到数据库,文件等 11 | //解决:捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。 12 | //使用场景: 游戏存副本等 13 | 14 | //实例:游戏状态恢复 15 | 16 | //游戏备份 17 | type Memento interface { 18 | Save(*Game) //存档 19 | Load() *Game //载入 20 | } 21 | 22 | //游戏 23 | type Game struct { 24 | Hp int 25 | Mp int 26 | } 27 | 28 | //初始化游戏 29 | func GameInit() *Game { 30 | return &Game{} 31 | } 32 | 33 | //玩游戏 34 | func (g *Game) Play(mpDelta, hpDelta int) { 35 | g.Mp += mpDelta 36 | g.Hp += hpDelta 37 | } 38 | 39 | //游戏状态 40 | func (g *Game) Status() { 41 | fmt.Printf("Current HP:%d, MP:%d\n", g.Hp, g.Mp) 42 | } 43 | 44 | //游戏备份 45 | type GameMemento struct { 46 | } 47 | 48 | func (gm *GameMemento) Save(game *Game) { 49 | f, err := os.Create("game.bak") 50 | if err != nil { 51 | panic(err) 52 | } 53 | enc := gob.NewEncoder(f) 54 | err = enc.Encode(game) 55 | if err != nil { 56 | panic(err) 57 | } 58 | } 59 | 60 | func (gm *GameMemento) Load() *Game { 61 | game := &Game{} 62 | f, err := os.Open("game.bak") 63 | if err != nil { 64 | panic(err) 65 | } 66 | dec := gob.NewDecoder(f) 67 | err = dec.Decode(game) 68 | if err != nil { 69 | panic(err) 70 | } 71 | return game 72 | } 73 | -------------------------------------------------------------------------------- /interperter/interperter.go: -------------------------------------------------------------------------------- 1 | //解释器模式 2 | package interperter 3 | 4 | import "strings" 5 | 6 | //意图:给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。 7 | //主要解决:对于一些固定文法构建一个解释句子的解释器。 8 | //何时使用:如果一种特定类型的问题发生的频率足够高,那么可能就值得将该问题的各个实例表述为一个简单语言中的句子。这样就可以构建一个解释器,该解释器通过解释这些句子来解决该问题。 9 | //如何解决:构件语法树,定义终结符与非终结符。 10 | //关键代码:构件环境类,包含解释器之外的一些全局信息,一般是 HashMap。 11 | //应用实例:编译器、运算表达式计算。SQL 解析、符号处理引擎等 12 | //优点: 1、可扩展性比较好,灵活。 2、增加了新的解释表达式的方式。 3、易于实现简单文法。 13 | //缺点: 1、可利用场景比较少。 2、对于复杂的文法比较难维护。 3、解释器模式会引起类膨胀。 4、解释器模式采用递归调用方法。 14 | //使用场景: 1、可以将一个需要解释执行的语言中的句子表示为一个抽象语法树。 2、一些重复出现的问题可以用一种简单的语言来进行表达。 3、一个简单语法需要解释的场景。 15 | 16 | //实例:判断特定的文本是否符合正确 17 | 18 | type Expression interface { 19 | Interpret(context string) bool 20 | } 21 | 22 | type TerminalExpression struct { 23 | Word string 24 | } 25 | 26 | // 终结符 27 | func (te *TerminalExpression) Interpret(context string) bool { 28 | if strings.Contains(context, te.Word) { 29 | return true 30 | } 31 | return false 32 | } 33 | 34 | // 或 35 | type OrExpression struct { 36 | A Expression 37 | B Expression 38 | } 39 | 40 | func (oe *OrExpression) Interpret(context string) bool { 41 | return oe.A.Interpret(context) || oe.B.Interpret(context) 42 | } 43 | 44 | // 与 45 | type AndExpression struct { 46 | A Expression 47 | B Expression 48 | } 49 | 50 | func (ae *AndExpression) Interpret(context string) bool { 51 | return ae.A.Interpret(context) && ae.B.Interpret(context) 52 | } 53 | -------------------------------------------------------------------------------- /strategy/compute.go: -------------------------------------------------------------------------------- 1 | //选择不同的策略计算价格 2 | package strategy 3 | 4 | import ( 5 | "github.com/xiaomeng79/go-design-pattern/strategy/strate" 6 | "math" 7 | "regexp" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | //价格计算 13 | type PriceCompute struct { 14 | OriginalPrice float64 //原价 15 | PromotionType string //促销类型字符串:如:几折 满几减几 16 | strate strate.IStrategy //策略 17 | } 18 | 19 | //reg1 := `(^[0-9].*)折` 20 | //reg2 := `^满([\d]+.?[\d]*)减([\d]+.?[\d]*)` 21 | 22 | //由于浮点运算不准确,所以返回2位小数 23 | //返回计算后的价格 24 | func (p *PriceCompute) Do() float64 { 25 | r1 := regexp.MustCompile(`(^[0-9].*)折`) //打折 :8.8折 26 | r2 := regexp.MustCompile(`^满([\d]+.?[\d]*)减([\d]+.?[\d]*)`) //满减 : 满200.35减100 27 | p.PromotionType = strings.Replace(p.PromotionType, " ", "", -1) 28 | switch { 29 | case r1.MatchString(p.PromotionType): //打折 30 | s := r1.FindStringSubmatch(p.PromotionType) 31 | f, _ := strconv.ParseFloat(s[1], 64) 32 | p.strate = &strate.Discount{p.OriginalPrice, f} 33 | 34 | case r2.MatchString(p.PromotionType): //满减 35 | s := r2.FindStringSubmatch(p.PromotionType) 36 | f1, _ := strconv.ParseFloat(s[1], 64) 37 | f2, _ := strconv.ParseFloat(s[2], 64) 38 | p.strate = &strate.FullSub{p.OriginalPrice, f1, f2} 39 | default: 40 | return p.OriginalPrice //没有匹配的促销模式 41 | } 42 | return Round(p.strate.Compute(), 2) //取2位小数 43 | 44 | } 45 | 46 | //计算结果取小数的n位 47 | func Round(f float64, n int) float64 { 48 | n10 := math.Pow10(n) 49 | return math.Trunc((f+0.5/n10)*n10) / n10 50 | } 51 | -------------------------------------------------------------------------------- /facade/facade.go: -------------------------------------------------------------------------------- 1 | //外观模式 2 | package facade 3 | 4 | import "fmt" 5 | 6 | //意图:为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用 7 | //解决: 降低访问复杂系统的内部子系统时的复杂度,简化客户端与之的接口 8 | 9 | //实例:经典的实例:一台电脑,包含cpu,内存,硬盘等部件,若想要启动电脑,则先后必须启动cpu,memory,Disk等 10 | 11 | //心得: 外观模式就是接待人员,导游 12 | 13 | //1.外观模式的优点: 14 | // 15 | //(1)由于外观模式对外屏蔽了子系统的细节,因此外观模式降低了客户端对子系统使用的复杂性。 16 | // 17 | //(2)外观模式松散了客户端与子系统的耦合关系,让子系统内部的模块更易维护和扩展。 18 | // 19 | //(3)通过合理的使用外观模式,可以帮我们更好的划分访问的层次。 20 | // 21 | //2.外观模式的缺点: 22 | // 23 | //过多的或者不合理的使用外观模式容易让人产生困惑,到底是调用Facade好呢还是直接调用模块好?因此一定要合理使用外观模式。 24 | // 25 | //3.外观模式的应用场景: 26 | // 27 | //(1)当系统需要进行分层设计时可以考虑使用Facade模式。 28 | // 29 | //(2)在开发阶段,子系统可能会因为重构变得越发复杂,此时可以通过外观模式对外提供一个简单的接口,减少系统之间的依赖。 30 | // 31 | //(3)在维护一个遗留的大型系统时,可能这个系统已经变得非常难以维护和扩展,此时可以考虑为新系统开发一个Facade类,来提供遗留系统的比较清晰简单的接口,让新系统与Facade类交互。 32 | 33 | //cpu 34 | type cpu struct{} 35 | 36 | func (c cpu) startup() { 37 | fmt.Println("cpu startup") 38 | } 39 | func (c cpu) shutdown() { 40 | fmt.Println("cpu shutdown") 41 | } 42 | 43 | //memory 44 | type memory struct{} 45 | 46 | func (m memory) startup() { 47 | fmt.Println("memory startup") 48 | } 49 | func (m memory) shutdown() { 50 | fmt.Println("membory shutdown") 51 | } 52 | 53 | //使用外观模式 54 | 55 | type Computer struct { 56 | cpu cpu 57 | memory memory 58 | } 59 | 60 | //实例化computer 61 | func NewComputer() *Computer { 62 | return &Computer{cpu: cpu{}, memory: memory{}} 63 | } 64 | func (c *Computer) StartUp() { 65 | c.cpu.startup() 66 | c.memory.startup() 67 | } 68 | 69 | func (c *Computer) ShutDown() { 70 | c.cpu.shutdown() 71 | c.memory.shutdown() 72 | } 73 | -------------------------------------------------------------------------------- /abstractfactory/abstractfactory.go: -------------------------------------------------------------------------------- 1 | //抽象工厂模式 2 | package abstractfactory 3 | 4 | import "fmt" 5 | 6 | //意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类,用于生成产品族的工厂,所生成的对象是有关联的 7 | //解决:主要解决接口选择的问题 8 | 9 | //不足:产品族扩展非常困难,要增加一个系列的某一产品,既要在抽象的 Creator 里加代码,又要在具体的里面加代码。 10 | 11 | //实例:PC厂商是一个抽象工厂,是鼠标和键盘的组合,鼠标和键盘又是不同的工厂生产,抽象工厂就是将不同工厂生产的产品关联起来 12 | 13 | //鼠标接口 14 | type IMouse interface { 15 | SayMouseBrand() 16 | } 17 | 18 | //戴尔鼠标 19 | type DellMouse struct{} 20 | 21 | func (d DellMouse) SayMouseBrand() { 22 | fmt.Println("Dell Mouse") 23 | } 24 | 25 | //惠普鼠标 26 | type HpMouse struct{} 27 | 28 | func (h HpMouse) SayMouseBrand() { 29 | fmt.Println("Hp Mouse") 30 | } 31 | 32 | //键盘接口 33 | type IKeybo interface { 34 | SayKeyBoBrand() 35 | } 36 | 37 | //戴尔键盘 38 | type DellKeybo struct{} 39 | 40 | func (d DellKeybo) SayKeyBoBrand() { 41 | fmt.Println("Dell Keybo") 42 | } 43 | 44 | //惠普键盘 45 | type HpKeybo struct{} 46 | 47 | func (h HpKeybo) SayKeyBoBrand() { 48 | fmt.Println("Hp Keybo") 49 | } 50 | 51 | //抽象工厂 52 | type IPcFactory interface { 53 | CreateMouse() //创建鼠标 54 | CreateKeybo() //创建键盘 55 | } 56 | 57 | //惠普工厂,惠普鼠标 + 戴尔键盘 58 | type HpFactory struct { 59 | Mouse IMouse 60 | Keybo IKeybo 61 | } 62 | 63 | func (h *HpFactory) CreateMouse() { 64 | h.Mouse = HpMouse{} 65 | } 66 | 67 | func (h *HpFactory) CreateKeybo() { 68 | h.Keybo = DellKeybo{} 69 | } 70 | 71 | //戴尔工厂 戴尔鼠标 + 戴尔键盘 72 | type DellFactory struct { 73 | Mouse IMouse 74 | Keybo IKeybo 75 | } 76 | 77 | func (d *DellFactory) CreateMouse() { 78 | d.Mouse = HpMouse{} 79 | } 80 | 81 | func (d *DellFactory) CreateKeybo() { 82 | d.Keybo = DellKeybo{} 83 | } 84 | -------------------------------------------------------------------------------- /chain/chain.go: -------------------------------------------------------------------------------- 1 | //责任链模式 2 | package chain 3 | 4 | import "fmt" 5 | 6 | //意图:分离不同职责,并且动态组合相关职责 7 | //解决:职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了 8 | 9 | //角色: 10 | //抽象处理者角色(Handler):定义出一个处理请求的接口 11 | //具体处理者角色(ConcreteHandler):具体处理者接受到请求后,可以选择将该请求处理掉,或者将请求传给下一个处理者。因此,每个具体处理者需要保存下一个处理者的引用,以便把请求传递下去。 12 | 13 | //实例:采购货物,如果小于等于1000,部门经理审批,如果小于等于5000,副总经理审批,如果大于5000总经理审批 14 | 15 | //采购请求 16 | type PurchaseRequest struct { 17 | Amount float64 //采购金额 18 | } 19 | 20 | //处理请求接口 21 | type IHandler interface { 22 | ProcessRequest(request *PurchaseRequest) //处理请求 23 | } 24 | 25 | //部门清理处理 26 | type ManagerHandler struct { 27 | Successor IHandler //继承者 28 | } 29 | 30 | func (m *ManagerHandler) ProcessRequest(request *PurchaseRequest) { 31 | if m == nil { 32 | return 33 | } 34 | if request.Amount <= 1000.00 { 35 | fmt.Println("我是部门经理,我可以处理!") 36 | } else { 37 | m.Successor.ProcessRequest(request) 38 | } 39 | } 40 | 41 | //副总经理 42 | type ViceGeneralManagerHandler struct { 43 | Successor IHandler 44 | } 45 | 46 | func (m *ViceGeneralManagerHandler) ProcessRequest(request *PurchaseRequest) { 47 | if m == nil { 48 | return 49 | } 50 | if request.Amount <= 5000.00 { 51 | fmt.Println("我是副总经理,我可以处理!") 52 | } else { 53 | m.Successor.ProcessRequest(request) 54 | } 55 | } 56 | 57 | //总经理 58 | 59 | type GeneralManagerHandler struct { 60 | Successor IHandler 61 | } 62 | 63 | func (m *GeneralManagerHandler) ProcessRequest(request *PurchaseRequest) { 64 | if m == nil { 65 | return 66 | } 67 | if request.Amount > 5000.00 { 68 | fmt.Println("我是总经理,我可以处理!") 69 | } else { 70 | m.Successor.ProcessRequest(request) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /composite/composite.go: -------------------------------------------------------------------------------- 1 | //组合模式 2 | package composite 3 | 4 | import ( 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | //意图:统一对象和对象集,使得使用相同接口使用对象和对象集,使得接口具有一致性 10 | //解决: 客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。 11 | //优点: 1、高层模块调用简单。 2、节点自由增加 12 | //缺点:在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口 13 | 14 | //实例:公司/部门的实例,统一的接口公司管理,公司相当于树枝,部门相当于叶子 15 | //公司可以增加/删除部门(对象),部门不可以 16 | 17 | //组合接口(公司管理接口) 18 | 19 | type ICompany interface { 20 | Add(ICompany) //增加 21 | Remove(ICompany) //移除 22 | Display(int) //展示下级 23 | } 24 | 25 | //公共的部分 26 | type Company struct { 27 | Name string 28 | } 29 | 30 | //具体公司(树枝节点[根]) 31 | type RealCompany struct { 32 | Company 33 | list []ICompany 34 | } 35 | 36 | //新建一个公司 37 | func NewRealCompany(name string) *RealCompany { 38 | return &RealCompany{Company{Name: name}, []ICompany{}} 39 | } 40 | 41 | //实现接口 42 | func (r *RealCompany) Add(c ICompany) { 43 | if r == nil { 44 | return 45 | } 46 | r.list = append(r.list, c) 47 | } 48 | func (r *RealCompany) Remove(c ICompany) { 49 | if r == nil { 50 | return 51 | } 52 | for i, v := range r.list { 53 | if v == c { 54 | r.list = append(r.list[:i], r.list[i+1:]...) 55 | } 56 | } 57 | return 58 | } 59 | func (r *RealCompany) Display(depth int) { 60 | if r == nil { 61 | return 62 | } 63 | fmt.Println(strings.Repeat("-", depth), " ", r.Name) 64 | for _, val := range r.list { 65 | val.Display(depth + 2) 66 | } 67 | } 68 | 69 | //具体的部门(叶子节点) 70 | //新建一个部门 71 | type Department struct { 72 | Company 73 | } 74 | 75 | //新建一个部门 76 | func NewDepartment(name string) *Department { 77 | return &Department{Company{Name: name}} 78 | } 79 | 80 | //实现接口 81 | func (r *Department) Add(c ICompany) {} 82 | func (r *Department) Remove(c ICompany) {} 83 | func (r *Department) Display(depth int) { 84 | if r == nil { 85 | return 86 | } 87 | fmt.Println(strings.Repeat("-", depth), " ", r.Name) 88 | } 89 | -------------------------------------------------------------------------------- /iterator/iterator.go: -------------------------------------------------------------------------------- 1 | //迭代器模式 2 | package iterator 3 | 4 | import "fmt" 5 | 6 | //意图:提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。 7 | //主要解决:不同的方式来遍历整个整合对象。 8 | //何时使用:遍历一个聚合对象。 9 | //如何解决:把在元素之间游走的责任交给迭代器,而不是聚合对象。 10 | //关键代码:定义接口:hasNext, next。 11 | //优点: 1、它支持以不同的方式遍历一个聚合对象。 2、迭代器简化了聚合类。 3、在同一个聚合上可以有多个遍历。 4、在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代码。 12 | //缺点:由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。 13 | //使用场景: 1、访问一个聚合对象的内容而无须暴露它的内部表示。 2、需要为聚合对象提供多种遍历方式。 3、为遍历不同的聚合结构提供一个统一的接口。 14 | //注意事项:迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。 15 | //实例: 迭代一个聚合的人类的信息 16 | 17 | type Person struct { 18 | Name string 19 | Age int 20 | Enjoys string 21 | } 22 | 23 | type peopleIterator interface { 24 | first() *Person 25 | next() *Person 26 | } 27 | 28 | type Peoples struct { 29 | peoples []*Person 30 | } 31 | 32 | func (p *Peoples) Add(people ...*Person) { 33 | if p == nil { 34 | return 35 | } 36 | p.peoples = append(p.peoples, people...) 37 | } 38 | 39 | //创建迭代器 40 | func (p *Peoples) CreateIterator() *PeoplesIterator { 41 | if p == nil { 42 | return nil 43 | } 44 | return &PeoplesIterator{p, 0} 45 | } 46 | 47 | //人迭代器 48 | type PeoplesIterator struct { 49 | ps *Peoples 50 | index int 51 | } 52 | 53 | //first 54 | func (pi *PeoplesIterator) first() *Person { 55 | if pi == nil { 56 | return nil 57 | } 58 | if len(pi.ps.peoples) > 0 { 59 | pi.index = 0 60 | return pi.ps.peoples[pi.index] 61 | } 62 | return nil 63 | } 64 | 65 | //next 66 | func (pi *PeoplesIterator) next() *Person { 67 | if pi == nil { 68 | return nil 69 | } 70 | if len(pi.ps.peoples) > pi.index+1 { 71 | pi.index++ 72 | return pi.ps.peoples[pi.index] 73 | } 74 | return nil 75 | } 76 | 77 | func (pi *PeoplesIterator) Iterator() { 78 | for b := pi.first(); b != nil; b = pi.next() { 79 | fmt.Printf("姓名:%s,年龄:%d,爱好:%s\n", b.Name, b.Age, b.Enjoys) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /bridge/bridge.go: -------------------------------------------------------------------------------- 1 | //桥接模式 2 | package bridge 3 | 4 | import "fmt" 5 | 6 | //意图:将抽象部分与实现部分分离,使它们都可以独立的变化 7 | 8 | //解决:通过桥接模式,是抽象和实现之间建立一个关联关系 9 | 10 | //实例:有抽象的消息和消息的实现 11 | 12 | //区别: 13 | //1. Facade模式是为一个复杂系统提供一个简单的接口。 14 | //比如你要去博物馆参观,很多东西,你一个个到处去问每个东西的管理员很麻烦,所以你找一个导游,让他给你一个个介绍,你只要找到导游就好了。导游就是门面。 15 | //2. 适配器模式,引用一下GOF95中的话: 16 | //适配器模式是把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法工作的两个类能够工作到一起。 17 | //举个例子,例如变压器 18 | //3. Bridge模式: 19 | //GOF95中的桥梁模式的描述:桥梁模式的用意是"将抽象化与实现化脱耦,使的二者可以独立变化。 20 | //例如AWT的实现 21 | 22 | //不同的出发点: 23 | //桥接是先有桥,才有两端的东西,分离抽象化和实现,使两者的接口可以不同,目的是分离 24 | //适配是先有两边的东西,才有适配器,改变已有的两个接口,让他们相容 25 | 26 | //抽象的消息接口 27 | type MessageAbstract interface { 28 | SendMessage(text, to string) 29 | } 30 | 31 | //实现的消息接口 32 | type MessageImplementer interface { 33 | Send(text, to string) 34 | } 35 | 36 | //SMS消息 37 | type MessageSMS struct{} 38 | 39 | func (m *MessageSMS) Send(text, to string) { 40 | fmt.Printf("send %s to %s via SMS", text, to) 41 | } 42 | func ViaSMS() MessageImplementer { 43 | return &MessageSMS{} 44 | } 45 | 46 | //Email消息 47 | type MessageEmail struct{} 48 | 49 | func ViaEmail() MessageImplementer { 50 | return &MessageEmail{} 51 | } 52 | 53 | func (*MessageEmail) Send(text, to string) { 54 | fmt.Printf("send %s to %s via Email", text, to) 55 | } 56 | 57 | //抽象的实现 58 | type CommonMessage struct { 59 | method MessageImplementer 60 | } 61 | 62 | func NewCommonMessage(method MessageImplementer) *CommonMessage { 63 | return &CommonMessage{ 64 | method: method, 65 | } 66 | } 67 | 68 | func (m *CommonMessage) SendMessage(text, to string) { 69 | m.method.Send(text, to) 70 | } 71 | 72 | type UrgencyMessage struct { 73 | method MessageImplementer 74 | } 75 | 76 | func NewUrgencyMessage(method MessageImplementer) *UrgencyMessage { 77 | return &UrgencyMessage{ 78 | method: method, 79 | } 80 | } 81 | 82 | func (m *UrgencyMessage) SendMessage(text, to string) { 83 | m.method.Send(fmt.Sprintf("[Urgency] %s", text), to) 84 | } 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## go 设计模式 2 | 3 | [![Build Status](https://travis-ci.org/xiaomeng79/go-design-pattern.svg?branch=master)](https://travis-ci.org/xiaomeng79/go-design-pattern) 4 | [![GitHub license](https://img.shields.io/github/license/xiaomeng79/go-design-pattern.svg)](https://github.com/xiaomeng79/go-design-pattern/blob/master/LICENSE) 5 | [![GitHub issues](https://img.shields.io/github/issues/xiaomeng79/go-design-pattern.svg)](https://github.com/xiaomeng79/go-design-pattern/issues) [![GitHub stars](https://img.shields.io/github/stars/xiaomeng79/go-design-pattern.svg)](https://github.com/xiaomeng79/go-design-pattern/stargazers) ![go1.11](https://img.shields.io/badge/go-1.11-brightgreen.svg) 6 | 7 | 8 | #### 设计模式的六大原则 9 | 1、开闭原则 10 | 11 | 对扩展开放,对修改关闭,简而言之:使用接口和抽象类 12 | 13 | 2、里氏代换原则 14 | 15 | 任何基类可以出现的地方,子类一定可以出现 16 | 17 | 3、依赖倒转原则 18 | 19 | 针对接口编程,依赖于抽象而不依赖于具体 20 | 21 | 4、接口隔离原则 22 | 23 | 使用多个隔离的接口,比使用单个接口要好,降低耦合,参考io包 24 | 25 | 5、迪米特法则,又称最少知道原则 26 | 27 | 一个实体应当尽量少地与其他实体之间发生相互作用,使得系统功能模块相对独立 28 | 29 | 6、合成复用原则 30 | 31 | 尽量使用合成/聚合的方式,而不是使用继承 32 | 33 | *总结:多使用接口,接口组合,针对接口编程* 34 | 35 | #### 创建型模式 36 | 37 | - single 单例模式 38 | - abstractFactory 抽象工厂 39 | - builder 建造者模式 40 | - factoryMethod 工厂方法 41 | - prototype 原型模式 42 | - simpleFactory 简单工厂模式 43 | 44 | #### 结构型模式 45 | 46 | - adapter 适配器模式 47 | - bridge 桥接模式 48 | - composite 组合模式 49 | - decorator 装饰器模式 50 | - facade 外观模式 51 | - flyweight 享元模式 52 | - proxy 代理模式 53 | - options 选项模式 54 | 55 | #### 行为型模式 56 | 57 | - chain 责任链模式 58 | - command 命令模式 59 | - interperter 解释器模式 60 | - iterator 迭代器模式 61 | - mediator 中介者模式 62 | - memento 备忘录模式 63 | - observer 观察者模式 64 | - state 状态模式 65 | - strategy 策略模式 66 | - template 模板模式 67 | - visitor 访问者模式 68 | 69 | ##### 参考资料 70 | 71 | [tmrts](https://github.com/tmrts/go-patterns) 72 | 73 | [BPing](https://github.com/BPing/golang_design_pattern) 74 | 75 | [qibin0506](https://github.com/qibin0506/go-designpattern) 76 | 77 | [HCLAC](https://github.com/HCLAC/DesignPattern) 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /visitor/visitor.go: -------------------------------------------------------------------------------- 1 | //访问者模式 2 | package visitor 3 | 4 | import "fmt" 5 | 6 | //意图:主要将数据结构与数据操作分离,不同的访问者,操作同一个元素,结果不同 7 | //解决:稳定的数据结构和易变的操作耦合问题 8 | 9 | //访问者模式和策略模式的区别: 10 | //策略模式:上下文和算法是一对多的关系 如:算2个数的加减乘除,上下文就是者2个数,算法就是加减乘除 11 | //访问者模式:上下和算法是多对多的关系 12 | 13 | //实例:老板和会计查看这个月的总账,老板查看的是盈利多少钱,会计查看的是交了多少税 14 | 15 | // 访问接口 16 | type IVisitor interface { 17 | VisitConcreteElementA(ConcreteElementA) 18 | VisitConcreteElementB(ConcreteElementB) 19 | } 20 | 21 | // 具体访问者A 22 | type ConcreteVisitorA struct { 23 | name string 24 | } 25 | 26 | func (c *ConcreteVisitorA) VisitConcreteElementA(ce ConcreteElementA) { 27 | if c == nil { 28 | return 29 | } 30 | fmt.Println(ce.name, c.name) 31 | ce.OperatorA() 32 | } 33 | 34 | func (c *ConcreteVisitorA) VisitConcreteElementB(ce ConcreteElementB) { 35 | if c == nil { 36 | return 37 | } 38 | fmt.Println(ce.name, c.name) 39 | ce.OperatorB() 40 | } 41 | 42 | // 具体访问者B 43 | type ConcreteVisitorB struct { 44 | name string 45 | } 46 | 47 | func (c *ConcreteVisitorB) VisitConcreteElementA(ce ConcreteElementA) { 48 | if c == nil { 49 | return 50 | } 51 | fmt.Println(ce.name, c.name) 52 | ce.OperatorA() 53 | } 54 | 55 | func (c *ConcreteVisitorB) VisitConcreteElementB(ce ConcreteElementB) { 56 | if c == nil { 57 | return 58 | } 59 | fmt.Println(ce.name, c.name) 60 | ce.OperatorB() 61 | } 62 | 63 | // 元素接口 64 | type IElement interface { 65 | Accept(IVisitor) 66 | } 67 | 68 | // 具体元素A 69 | type ConcreteElementA struct { 70 | name string 71 | } 72 | 73 | func (c *ConcreteElementA) Accept(visitor IVisitor) { 74 | if c == nil { 75 | return 76 | } 77 | visitor.VisitConcreteElementA(*c) 78 | } 79 | func (c *ConcreteElementA) OperatorA() { 80 | if c == nil { 81 | return 82 | } 83 | fmt.Println("OperatorA") 84 | } 85 | 86 | // 具体元素B 87 | type ConcreteElementB struct { 88 | name string 89 | } 90 | 91 | func (c *ConcreteElementB) Accept(visitor IVisitor) { 92 | if c == nil { 93 | return 94 | } 95 | visitor.VisitConcreteElementB(*c) 96 | } 97 | func (c *ConcreteElementB) OperatorB() { 98 | if c == nil { 99 | return 100 | } 101 | fmt.Println("OperatorB") 102 | } 103 | 104 | // 维护元素集合 105 | type ObjectStructure struct { 106 | list []IElement 107 | } 108 | 109 | func (o *ObjectStructure) Attach(e IElement) { 110 | if o == nil || e == nil { 111 | return 112 | } 113 | o.list = append(o.list, e) 114 | } 115 | 116 | func (o *ObjectStructure) Detach(e IElement) { 117 | if o == nil || e == nil { 118 | return 119 | } 120 | for i, val := range o.list { 121 | if val == e { 122 | o.list = append(o.list[:i], o.list[i+1:]...) 123 | break 124 | } 125 | } 126 | } 127 | 128 | func (o *ObjectStructure) Accept(v IVisitor) { 129 | if o == nil { 130 | return 131 | } 132 | for _, val := range o.list { 133 | val.Accept(v) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------