package main
import"fmt"type vehicle interface{run()}type Factory struct{}func(f *Factory)GetVehicle(v string) vehicle {switch v {case"CAR":returnnew(car)case"BIKE":returnnew(bike)default:returnnew(car)}}type car struct{}func(c *car)run(){
fmt.Println("car is running")}type bike struct{}func(b *bike)run(){
fmt.Println("bike is running")}funcmain(){
f :=new(Factory)
b := f.GetVehicle("BIKE")
b.run()}
单例模式
type bike struct{
ID int}var(
once sync.Once
singleton *bike
)funcGetSingleton()*bike {
once.Do(func(){
singleton =new(bike)})return singleton
}funcmain(){
b :=GetSingleton()
b.ID =1
b =GetSingleton()
fmt.Println(b.ID)}
对象池模式
type bike struct{
ID int}type bikePool struct{
pool sync.Pool
}funcNewBikePool()*bikePool {
p :=new(bikePool)
p.pool = sync.Pool{
New:func()interface{}{returnnew(bike)},}return p
}func(p *bikePool)Get()*bike {return p.pool.Get().(*bike)}func(p *bikePool)Put(b *bike){//may clear b//b.ID = 0
p.pool.Put(b)}funcmain(){
p :=NewBikePool()
b := p.Get()
fmt.Println(b)
p.Put(b)}
type run interface{run(string)}type adapter struct{
r1 run
}func(a *adapter)run(e int){
energy :=""switch e {case1:
energy ="oil"case2:
energy ="electricity"}
a.r1.run(energy)}type car struct{}func(c *car)run(energy string){if energy !="oil"{
fmt.Printf("car can't run with %s!\n",energy)return}
fmt.Println("car is running")}funcmain(){
c :=&car{}
a := adapter{
r1: c,}
a.run(1)}
代理模式
package main
import("fmt")type car struct{
color string}func(c *car)run(){
fmt.Printf("%s car is running",c.color)}type CarProxy struct{
c car
}func(c *CarProxy)run(){
c.c.run()}funcNewCarProxy(color string)*CarProxy {return&CarProxy{
car{color: color},}}funcmain(){
p :=NewCarProxy("red")
p.run()}
装饰器模式
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活
package main
//echo的middleware就是这种模式type abs func(int)intfuncdecorator(o abs) abs {returnfunc(a int)int{if a <0{
a =-a
}returno(a)}}funcmain(){
f :=func(a int)int{return a
}
fmt.Println(f(-1))
f =decorator(f)
fmt.Println(f(-1))}
type vehicle interface{run()}type decorator struct{
v vehicle
}func(d *decorator)run(){
fmt.Println("decorated")
d.v.run()}type car struct{}func(c *car)run(){
fmt.Println("car is running")}funcmain(){
c :=&car{}
d :=&decorator{c}
d.run()}