vendredi 22 octobre 2021

Conditional parameter without using if-else?

I have a program that is working fine at the moment.

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

Now I need to make it accept parameters in cli mode. e.g. python example.py --strategy=fly

I can code like this but it violates the purpose that I used strategy pattern at the start. I want to reduce the unnecessary if-else as much as possible.

if args.strategy == "fly":
    strategy = FlyStrategy()
elif args.strategy == "walk":
    strategy = WalkStrategy()

Aucun commentaire:

Enregistrer un commentaire