设计策略模式

策略模式

介绍

假如一个人要出去旅游,交通工具有很多种,可以开车、走路、坐飞机等等,这个时候使用哪种交通工具就是一种策略,交通工具是可以扩展的,为了满足这种情况我们可以使用策略模式。

假如切一块肉,可以使用锯子、小刀、菜刀等,使用哪种工具就是一种策略。

python实现

# 策略模式
class Transportation:
    def use(self):
        pass

class Person(object):
    way = None

    def set_way(self, way: Transportation):
        self.way = way
        print(f"设置交通工具【{way}】成功")

    def use_way(self):
        self.way.use()

class Walk(Transportation):
    def use(self):
        print("步行")

class Boat(Transportation):
    def use(self):
        print("坐船")

if __name__ == '__main__':
    p = Person()
    w = Walk()
    b = Boat()
    p.set_way(w)
    p.use_way()
    p.set_way(b)
    p.use_way()
    print("-----------------")

go实现

package main

import "fmt"

// 交通工具
type Transportation interface {
	Use()
}
type Boat struct {
}

func (b *Boat) Use() {
	fmt.Println("使用船")
}

type Walk struct {
}

func (w *Walk) Use() {
	fmt.Println("使用步行")
}

// 定义人
type Person struct {
	way Transportation
}

func (p *Person) SetWay(way Transportation) {
	p.way = way
}
func (p *Person) UseWay() {
	p.way.Use()
}

// 策略模式
func main() {
	// 创建人对象
	p := Person{}
	//创建交通工具
	b := new(Boat)
	w := Walk{}
	p.SetWay(b)
	p.UseWay()
	p.SetWay(&w)
	p.UseWay()
}

总结

那些频繁切换方法使用的情况可以使用策略模式

你可能感兴趣的:(设计模式,go,python,策略模式)