iamgm
iamgm

Reputation: 41

Refactoring. Trying to make code more elegant. Need design pattern

Without going into detail. I have structure like this:

class someClass():
    def __init__(self, m):
        
        if m == 1:
            self.mode1()
        elif m == 2:
            self.mode2()
        elif m == 3:
            self.mode3()
        .....

        elif m == 10:
            self.mode10()

It's a class with different operating modes. Passing variable m to the class I want to set mode of operation running corresponding method of class. Is there way to do this more elegant and get rid of the 'if' statements? May be there is some design pattern for this specific case?

Upvotes: 0

Views: 68

Answers (1)

iamgm
iamgm

Reputation: 41

Eventually I used strategy pattern. Thanks @Robin for advice.

class Strategy(ABC):
    @abstractmethod
    def execute(self):
        pass   

class Context():
    def __init__(self, strategy: Strategy):
        self._strategy = strategy

    @property
    def strategy(self):
        return self._strategy

    @strategy.setter
    def strategy(self,  strategy: Strategy):
        self._strategy = strategy

    def executeStrategy(self):
        self._strategy.execute()

class mode0(Strategy):
    def execute(self):
        logging.info("MODE 0")
        
class mode1(Strategy):
    def execute(self):
        logging.info("MODE 1")
        
class mode2(Strategy):
    def execute(self):
        logging.info("MODE 2")
        
.....

then

class someClass():
    def __init__(self, m):
        modesList = [mode0, mode1, mode2, mode3, mode4, mode5, 
                     mode6, mode7, mode8, mode9, mode10, mode11]      
    
        ctx = Context(modesList[m]())
        ctx.executeStrategy()
    

Upvotes: 1

Related Questions