mardi 22 juin 2021

is there a good design pattern for this classes relation in Python?

So imagine I have a class A, and class B can take class A as its member and use class A's functionality to do the job, like this

 class B:
    def __init__(self, A):
        self.A = A

    def do_something(self):
        # some other jobs ....
        self.A.do_the_job()

This is a straightforward design. However, in my case, class A can be accessed and modified outside of B as well, then this design is a little strange because although A is a member class of B, actually A could be changing its status outside of B. Therefore I change it to this design

 class B:
    def __init__(self):
        pass

    def do_something(self, A):
        # some other jobs ....
        A.do_the_job()

It is definitely perfectly fine, the only ugly thing is, right now everytime when I call B.do_something, I need to pass class A as its argument. Actually class B has several other functions that will use class A as well.

I wonder if there is any better design pattern to deal with this kind of situation?

Aucun commentaire:

Enregistrer un commentaire