vendredi 9 mars 2018

Design pattern to use for "create if not existing"?

I'm comparing records in database A to database B, so that B can be synced to A. If for whatever reason B is different from A, I create a new object containing only the attributes to be updated. (in this example, the application I'm writing does NOT do the updating, it simply creates a file of the necessary changes.)

Something like this is what I'm thinking... (code is simplified here...)

class Foo()
    ...
    def change_or_create(self,id,value):
        # append if exist or create object to self.dictionary?
    ...


foo = Foo()

attributes_to_check = ('first_name','last_name')

for A_row in session.query(A).all():
    for B_row in session.query(B).one():
        for item in attributes_to_check:
            A_value = getattr(A_row, item)
            B_value = getattr(B_row, item)
            if (A_value != B_value):
                foo.change_or_create(A_row.id,A_value)

# write objects needing updating to disk

I'm new to design patterns, and I'm wanting to start implementing them in my code, correctly. It feels like either a singleton or factory pattern could be useful here, or something similar. Am I on the right page with that thought? Is there a specific, common design pattern that solves this?

Is it common to have a singleton which then holds a list\dictionary of objects? Or should I just be putting those in a dictionary that's not buried in an object? if A_value.id not in update_dict...

Aucun commentaire:

Enregistrer un commentaire