创建型模式
工厂模式
package main
import "fmt"
type vehicle interface {
run()
}
type Factory struct {}
func (f *Factory) GetVehicle(v string) vehicle {
switch v {
case "CAR":
return new(car)
case "BIKE":
return new(bike)
default:
return new(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")
}
func main() {
f := new(Factory)
b := f.GetVehicle("BIKE")
b.run()
}
单例模式
type bike struct {
ID int
}
var (
once sync.Once
singleton *bike
)
func GetSingleton() *bike {
once.Do(func() {
singleton = new(bike)
})
return singleton
}
func main() {
b := GetSingleton()
b.ID = 1
b = GetSingleton()
fmt.Println(b.ID)
}
对象池模式
type bike struct {
ID int
}
type bikePool struct {
pool sync.Pool
}
func NewBikePool() *bikePool {
p := new(bikePool)
p.pool = sync.Pool{
New: func() interface{} {
return new(bike)
},
}
return p
}
func (p *bikePool) Get() *bike {
return p.pool.Get().(*bike)
}
func (p *bikePool) Put(b *bike) {
p.pool.Put(b)
}
func main() {
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 {
case 1:
energy = "oil"
case 2:
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")
}
func main() {
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()
}
func NewCarProxy(color string) *CarProxy {
return &CarProxy{
car{color: color},
}
}
func main() {
p := NewCarProxy("red")
p.run()
}
装饰器模式
- 动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活
package main
type abs func(int)int
func decorator(o abs) abs {
return func(a int) int {
if a < 0 {
a = -a
}
return o(a)
}
}
func main() {
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")
}
func main() {
c := &car{}
d := &decorator{c}
d.run()
}
|