dimanche 1 octobre 2023

Correct use of python strategy pattern to introduce custom logic

I have a dataclass that creates an instance with a lot of attributes. They initially all have default values but if a certain flag is given then some of the attributes values will change from some custom methods. I haven't used the strategy pattern in python before but this looks like a good opportunity to use it. Can anyone explain to me if my thinking is accurate or if I'm thinking about this wrong. Based on my research this is a perfectly good way to introduce custom logic.

Module 1:

@dataclass
class PtIrl(Data):

    data_id: int
    id: uuid.UUID
    person: str
    address: str
    zip_code: str
        game: str
...............
@staticmethod
    def create(
        options: data_options
    )
        new_irl = []
        for i in enumerate(irl):
           
            searching = irl.get_all()
            
            if searching:
                irl = PtIrl(
                    data_id=options.data_id,
                    id=uuid,
                    person=f"{person.name_first} {person.name_last}",
                    address=data.address(),
                    zip_code=data.randomZip(),
                    game=data.randomGame(),
.....................................

                    if options.custom == flag.FIRST:
                        strategy = CUSTOM_LOGIC_FIRST()
                        elif options.custom == flag.SECOND():
                        strategy = CUSTOM_LOGIC_SECOND()
                        elif options.custom == flag.THIRD():
                                                .......
    
                        strategy = None

                        if strategy:
                           strategy.apply(irl)
                        new_irl.append(irl)
        return new_irl

Module 2:

class CustomLogic(ABC):
    @abstractmethod
    def apply(self, ir, *args):
        pass


class CustomLogicFirst(CustomLogic):
    def __init__(self, seed=None):
        self.rnd = random.Random(seed)

    def set_new_custom_zip(self, irl):
       #logic to get custom zips
        
    def set_new_custom_game(self,irl):
        #logic to get custom games

    def apply(self, irl):
        self.set_new_custom_zip(irl)
        self.set_new_custom_game(irl)


class CustomLogicSecond(CustomLogic):
    def apply(self, irl):
        pass

class CustomLogicThird(CustomLogic):
    def apply(self, irl):
        pass

Aucun commentaire:

Enregistrer un commentaire