面试题答案
一键面试高阶函数和装饰器在策略模式中的应用原理
-
高阶函数:高阶函数是指可以接受一个或多个函数作为参数,并且/或者返回一个函数作为结果的函数。在策略模式中,高阶函数可以用来封装不同的策略逻辑,使得这些策略逻辑可以像数据一样被传递和使用。例如,我们可以将不同的算法函数作为参数传递给一个高阶函数,这个高阶函数可以根据不同的条件调用不同的算法函数,从而实现不同的策略。
-
装饰器:装饰器本质上是一个高阶函数,它可以在不修改原函数代码的情况下,为原函数添加额外的功能。在策略模式中,装饰器可以用来注册不同的策略函数。通过装饰器,我们可以将策略函数注册到一个字典或者其他数据结构中,这样在运行时可以根据需要动态地选择并调用相应的策略函数。
策略模式代码示例
# 存储策略的字典
strategy_dict = {}
def register_strategy(func):
"""
装饰器函数,用于注册策略
"""
strategy_dict[func.__name__] = func
return func
@register_strategy
def strategy1(x, y):
return x + y
@register_strategy
def strategy2(x, y):
return x * y
def execute_strategy(strategy_name, x, y):
"""
根据策略名称执行相应的策略
"""
if strategy_name in strategy_dict:
return strategy_dict[strategy_name](x, y)
else:
raise ValueError(f"策略 {strategy_name} 未定义")
# 示例使用
result1 = execute_strategy('strategy1', 2, 3)
result2 = execute_strategy('strategy2', 2, 3)
print(result1) # 输出: 5
print(result2) # 输出: 6
在上述代码中:
register_strategy
是一个装饰器,它将被装饰的函数注册到strategy_dict
中。strategy1
和strategy2
是两个不同的策略函数,通过@register_strategy
装饰器注册到策略字典中。execute_strategy
函数根据传入的策略名称,从strategy_dict
中获取相应的策略函数并执行。