设计策略模式

策略模式

介绍

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

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

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

总结

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

相关推荐
周努力.21 小时前
设计模式之策略模式
设计模式·策略模式
Pasregret1 天前
策略模式:动态切换算法的设计智慧
算法·bash·策略模式
Leaf吧3 天前
java 设计模式 策略模式
java·设计模式·策略模式
knowledgebao3 天前
osxcross 搭建 macOS 交叉编译环境
macos·策略模式
〆、风神8 天前
Spring Boot实战:基于策略模式+代理模式手写幂等性注解组件
spring boot·代理模式·策略模式
邪恶的贝利亚9 天前
设计模式实践:模板方法、观察者与策略模式详解
设计模式·策略模式
进击的圆儿9 天前
策略模式简单介绍
策略模式
死也不注释9 天前
【设计模式——策略模式】
设计模式·策略模式
未定义.22112 天前
Java设计模式实战:策略模式在SimUDuck问题中的应用
java·设计模式·策略模式
爱叨叨的程序狗12 天前
策略模式随笔~
策略模式