不使用 if-else 的条件参数?
Conditional parameter without using if-else?
我有一个目前运行良好的程序。
from abc import ABC, abstractmethod
class User():
def __init__(self, transport_strategy):
self.transport_strategy = transport_strategy
def transport(self):
self.transport_strategy.transport()
class TransportStrategy():
@abstractmethod
def transport(self):
pass
class WalkStrategy(TransportStrategy):
def transport(self):
print("I walk")
class FlyStrategy(TransportStrategy):
def transport(self):
print("I fly")
if __name__ == "__main__":
u1 = User(FlyStrategy())
u1.transport()
u2 = User(WalkStrategy())
u2.transport()
现在我需要让它在cli 模式下接受参数。
例如python example.py --strategy=fly
我可以这样写代码,但这违背了我一开始使用策略模式的目的。我想尽量减少不必要的if-else
if args.strategy == "fly":
strategy = FlyStrategy()
elif args.strategy == "walk":
strategy = WalkStrategy()
如果我理解了问题,你可以使用字典
strategies = {
"fly": FlyStrategy
"walk": WalkStrategy
}
if args.strategy not in strategies:
raise ValueError(f'Unknown strategy: {args.strategy}')
strategy = strategies[args.strategy]()
我有一个目前运行良好的程序。
from abc import ABC, abstractmethod
class User():
def __init__(self, transport_strategy):
self.transport_strategy = transport_strategy
def transport(self):
self.transport_strategy.transport()
class TransportStrategy():
@abstractmethod
def transport(self):
pass
class WalkStrategy(TransportStrategy):
def transport(self):
print("I walk")
class FlyStrategy(TransportStrategy):
def transport(self):
print("I fly")
if __name__ == "__main__":
u1 = User(FlyStrategy())
u1.transport()
u2 = User(WalkStrategy())
u2.transport()
现在我需要让它在cli 模式下接受参数。
例如python example.py --strategy=fly
我可以这样写代码,但这违背了我一开始使用策略模式的目的。我想尽量减少不必要的if-else
if args.strategy == "fly":
strategy = FlyStrategy()
elif args.strategy == "walk":
strategy = WalkStrategy()
如果我理解了问题,你可以使用字典
strategies = {
"fly": FlyStrategy
"walk": WalkStrategy
}
if args.strategy not in strategies:
raise ValueError(f'Unknown strategy: {args.strategy}')
strategy = strategies[args.strategy]()