lundi 22 mai 2017

how to save redundant calculations for coupled classes with composition

I have several classes that are coupled to each other and I would like to have a design that minimizes redundancy in them.

Right now the design is as follows. The classes are

  • A
  • C, D
  • AC, AD: compositions of (A, C) and (A, D)

where all classes are initialized with the same data, each class performed some calculations and saves its own result. More specifically, users would create instances of A, AC, AD but not C and D. In other words, to the user, A, AC, AD are similar things and have uniform interface, whereas C and D are hidden. Here the logic is that, for example, the result of C is not useful unless we exclude the result of A from it. Some mock-up code is as follows

class A(object):
    def __init__(self, data):
        # some work
    def postproc(self, *args):
        # some real work
        self.result = ..

class AC(object):
    def __init__(self, data):
        self.a = A(data)
        self.c = C(data)
    def postproc(self, *args):
        result_a = self.a.postproc(*args[:3])
        result_c = self.c.postproc(*args[3:])
        self.result = exclude_c_from_a(result_a, result_c)

With the current design, if the user create instances of A and AC, (or AC and AD, or other combinations), the calculation of A is done multiple times. I would like to have no redundant calculations, how should the design be changed?

A little more details on the usage: there will be multiple instances of A with different initial data too. Thus I cannot use singleton to guarantee there is only one A instance.

Aucun commentaire:

Enregistrer un commentaire