设计策略模式

策略模式

介绍

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

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

python实现

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实现

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()
}

总结

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

相关推荐
shichen5012 天前
MacOS 如何映射快捷键
macos·mac·策略模式
Tiantangbujimo75 天前
2.策略模式(Strategy)
策略模式
咖啡の猫7 天前
策略模式
设计模式·策略模式
随心但不率性7 天前
macos app签名和公证
macos·策略模式
博一波13 天前
【设计模式-行为型】策略模式
设计模式·策略模式
想要打 Acm 的小周同学呀13 天前
JDBCTemplate-模板设计模式和策略模式
设计模式·策略模式
黑客老陈15 天前
Electron的应用安全测试基础 | 安装与检测基于Electron的应用程序
开发语言·javascript·网络·安全·web安全·electron·策略模式
我是苏苏18 天前
设计模式03:行为型设计模式之策略模式的使用情景及其基础Demo
设计模式·策略模式
power-辰南18 天前
设计模式之策略模式
设计模式·策略模式
hlvy18 天前
如何使用策略模式并让spring管理
java·开发语言·后端·spring·策略模式