设计策略模式

策略模式

介绍

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

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

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

总结

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

相关推荐
头发还在的女程序员6 天前
【免费下载】企业能源管理系统
小程序·策略模式·能源管理
前端 贾公子6 天前
React 和 Vue 都离不开的表单验证库 async-validator 之策略模式的应用 (上)
vue.js·react.js·策略模式
小米4967 天前
Js设计模式---策略模式
设计模式·策略模式
geovindu7 天前
python: Strategy Pattern
python·设计模式·策略模式
Hello.Reader10 天前
Flink 任务失败恢复机制Restart Strategy 和 Failover Strategy 怎么配才“又稳又不炸”
大数据·flink·策略模式
武帝为此12 天前
【Linux strace命令介绍】
linux·运维·策略模式
带娃的IT创业者13 天前
解密OpenClaw系列10-OpenClawSparkle框架集成
软件工程·agent·策略模式·自动更新·ai智能体·智能体开发·openclaw
茶本无香14 天前
【无标题】
java·设计模式·策略模式
驴儿响叮当201016 天前
设计模式之策略模式
设计模式·策略模式
kong790692817 天前
设计模式-策略模式
设计模式·策略模式·行为设计模式