jeudi 15 octobre 2020

Better design pattern instead of factory/strategy?

Let's say I have a pd.Series object and I want to apply some functionality to the series. In the following example, I would like to apply a histogram and a mean to a series. I have used the following code:

class Mean:
    
    def do(self, series):
        return series.mean()
    
    
class Histogram:
    
    def do(self, series, **kwargs):
        fig, ax = plt.subplots(1, 1)
        ax = series.plot(kind='hist', **kwargs)
        plt.close()
        return ax.figure

class FunctionPicker:
    
    def pick(self, functionality):
        if functionality == 'histogram':
            return Histogram()
        elif functionality == 'mean':
            return Mean()
        


class S:
    
    def __init__(self, series):
        self.series = series
        
    def run(self, functionality, **kwargs):
        picked_func = FunctionPicker().pick(functionality)
        return picked_func.do(self.series, **kwargs)

What I don't really like in this implementation is that in the S class I have to provide the *kwargs argument, which will never be used for the Mean class. Is this a correct approach or there are other design more appropriate?

Aucun commentaire:

Enregistrer un commentaire