Strategy(策略)
2024-09-07 00:36:27
意图:
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
适用性:
许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间/时间权衡的算法。当这些变体实现为一个算法的类层次时[H087] ,可以使用策略模式。
算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
一个类定义了多种行为, 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的Strategy类中以代替这些条件语句。
#!/usr/bin/python
#coding:utf8
"""
Strategy
In most of other languages Strategy pattern is implemented via creating some base strategy interface/abstract class and
subclassing it with a number of concrete strategies (as we can see at http://en.wikipedia.org/wiki/Strategy_pattern),
however Python supports higher-order functions and allows us to have only one class and inject functions into it's
instances, as shown in this example.
"""
import types class StrategyExample:
def __init__(self, func=None):
self.name = 'Strategy Example 0'
if func is not None:
self.execute = types.MethodType(func, self) def execute(self):
print(self.name) def execute_replacement1(self):
print(self.name + ' from execute 1') def execute_replacement2(self):
print(self.name + ' from execute 2') if __name__ == '__main__':
strat0 = StrategyExample() strat1 = StrategyExample(execute_replacement1)
strat1.name = 'Strategy Example 1' strat2 = StrategyExample(execute_replacement2)
strat2.name = 'Strategy Example 2' strat0.execute()
strat1.execute()
strat2.execute()
最新文章
- Elasticsearch 字段数据类型
- JavaScript(三)——DOM操作一
- 学习SQL的点点滴滴(三)-修改数据库的兼容级别
- 【HACK】破解APK并注入自己的代码
- 从数列1,2,3.......n 中 随意取几个数,使其和等于 m
- C# and Redis,安装作为服务
- 用g++ 编译 ffmpeg 编译出现 error: 'UINT64_C' was not declared in this scope 或 missing -D__STDC_CONSTANT_MACROS
- java.lang.OutOfMemoryError: Java heap space错误和方法(集、转)
- Hibernate 系列教程14-继承-PerTable策略
- Katana-CookieAuthenticationMiddleware-源码浅析
- php redis 处理websocket聊天记录
- 1.9 From Native to HTML5
- java在cmd下编译引用第三方jar包
- [Swift]在Swift项目中创建桥接头文件,Swift文件和Objective-C文件相互调用
- 廖雪峰Java4反射与泛型-3范型-6super通配符
- angularJs实现动态增加输入框
- 【docker】docker部署spring boot服务 选择配置文件启动
- 18、Java中可变参数
- 34.TokenInterceptor防止表单重复提交
- Apache mahout 源码阅读笔记-DataModel之UserBaseRecommender
热门文章
- 二进制状态压缩dp(旅行商TSP)POJ3311
- 次小生成树(poj1679)
- AWR之-enq TX - row lock contention的性能故障-转
- nginx 下使用 bootstrap 字体的问题
- MTA---smtp(25,postfix,sendmail),Pop3(110,Devocot), MUA(foxmail) IMAP(server,client rsync)
- Treasure Exploration---poj2594(传递闭包Floyd+最小路径覆盖)
- python修改镜像源
- conda
- android 异步线程刷新UI 以及 JSON解析 以及 url get请求
- js-jquery-从SweetAlert到SweetAlert2