mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-21 20:36:01 +03:00
update code
This commit is contained in:
parent
178e5eff4c
commit
ffbfc177a7
@ -1,29 +1,35 @@
|
||||
// 外观模式 facade pattern.
|
||||
// 为多个子模块提供一个统一的调用接口,子模块可以是同一接口的实现也可以不同.
|
||||
// 实际上编写程序的时候很多地方不知不觉的会使用了模式.
|
||||
// 这里以购买鸡蛋,牛奶,小麦粉为例,从代购处一次性购买三种而不需要分别访问三个商店
|
||||
// 实际上编写程序的时候很多地方不知不觉的会使用该模式.
|
||||
// 这里以购买鸡蛋,牛奶,小麦粉为例,从代购处一次性购买三种食材而不需要分别访问三个商店,
|
||||
// SellAll()方法还可以将三处接口包装为原子操作,在购买失败时进行回滚
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Shop interface {
|
||||
Sell()
|
||||
Sell() error
|
||||
}
|
||||
|
||||
type EggShop struct {}
|
||||
|
||||
func (EggShop)Sell(){
|
||||
println("no more eggs left")
|
||||
func (EggShop)Sell() error{
|
||||
return errors.New("no more eggs left")
|
||||
}
|
||||
|
||||
type MilkShop struct {}
|
||||
|
||||
func (MilkShop)Sell(){
|
||||
println("no more milk left")
|
||||
func (MilkShop)Sell()error{
|
||||
return errors.New("no more milk left")
|
||||
}
|
||||
|
||||
type WheatFlourShop struct {}
|
||||
|
||||
func (WheatFlourShop)Sell(){
|
||||
println("no more wheat flour left")
|
||||
func (WheatFlourShop)Sell()error{
|
||||
return errors.New("no more wheat flour left")
|
||||
}
|
||||
|
||||
type DealerFacade struct {
|
||||
@ -32,10 +38,21 @@ type DealerFacade struct {
|
||||
WfShop Shop
|
||||
}
|
||||
|
||||
func (d DealerFacade)SellAll(){
|
||||
d.EgShop.Sell()
|
||||
d.MkShop.Sell()
|
||||
d.WfShop.Sell()
|
||||
func (d DealerFacade)BuyAll(){
|
||||
//if e := d.EgShop.Sell();e != nil{
|
||||
// log.Println(e)
|
||||
// RollBack()
|
||||
//}
|
||||
//...
|
||||
e1 := d.EgShop.Sell()
|
||||
e2 := d.MkShop.Sell()
|
||||
e3 := d.WfShop.Sell()
|
||||
if e1 == nil && e2 == nil && e3 == nil{
|
||||
//success
|
||||
}else{
|
||||
//fail and rollback
|
||||
fmt.Printf("error:\n%v\n%v\n%v" ,e1 ,e2 ,e3)
|
||||
}
|
||||
}
|
||||
|
||||
func main(){
|
||||
@ -44,7 +61,14 @@ func main(){
|
||||
MilkShop{},
|
||||
WheatFlourShop{},
|
||||
}
|
||||
dealer.SellAll()
|
||||
dealer.BuyAll()
|
||||
/*
|
||||
output:
|
||||
error:
|
||||
no more eggs left
|
||||
no more milk left
|
||||
no more wheat flour left
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
// 享元模式 flyweight pattern.
|
||||
// 通过保存不同特征的实例以达到复用的效果,从而节省内存和优化性能.
|
||||
// 与对象池模式的不同之处在于享元模式所保存的实例具有不同的特征,而对象池则全部是相同的实例.
|
||||
// 这里以蛋糕为例,字段flavour为其味道,根据不同的制作者将不同的实例保存起来.
|
||||
// 这里以蛋糕为例,字段flavour为其味道,根据不同的味道作为不同的实例保存起来.
|
||||
// 当实例的特征较少时,享元模式还可以和单例模式相结合.
|
||||
package main
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user