mardi 21 février 2023

Different number of parameters in Strategy Pattern

I am adopting strategy pattern in coding some filtering logics:

  1. filterByEventName(event, request), where filter is done by matching event.name and request.name;

  2. filerByEventDate(event, request), where filter is done by matching event.date and request.date;

  3. filterByEventDist(event, request, k), where filter is done by calculating the distance between event.longitude and event.latitude and request.longitude and request.latitude, and return the top k closest ones

I have the strategy pattern designed like below:

class Strategy(ABC):
    @abstractmethod
    def filter(self, *args):
        pass

class StrategyByEventName(Strategy):
    def filter(self, events, request):
        ...

class StrategyByEventDate(Strategy):
    def filter(self, events, request):
        ...


class StrategyByEventDist(Strategy):
    def filter(self, events, request, k):
        ...


class Context:
    def __init__(self, strategy, events, request):
        self.strategy = strategy
        self.events = events
        self.request = request

    def filterByType(self):
        events = self.strategy.filter(self.events, self.request)  


strategy: Strategy = StrategyByEventDate()
context: Context = Context(strategy, events, request)
context.filterByType()

strategy: Strategy = StrategyByEventDist()
context: Context = Context(strategy, events, request)
context.filterByType() # for StrategyByEventDist, where should I pass the parameter k? 

since the last strategy has different number of parameters as the first two, how should I design the call func filterByType to handle the additional parameter in StrategyByEventDist? Or I should not use strategy pattern here?

Aucun commentaire:

Enregistrer un commentaire