dimanche 11 décembre 2022

Design patterns for chaining dependency objects

I have a design problem and I can't find the right way to deal with that. In my problem there are 4 classes:

  • class G
  • class T depending on the G
  • class F depending on T
  • class P depending on G, T and F

Additionally each concrete implementation of P should use exact implementation of T and when F is used then T is not needed. However F and T are different concepts (I would say F is some transformation or different interpretation of T) and it is hard to design common interface for them (otherwise I would think about decorator pattern). I was thinking about approach like below:

class PImpl extends P {
     G g;
     T t;
     F f;

     PImpl(G g) {
        this.g = g;
        this.t = new TImpl(g);
        this.f = new FImpl(t);
     }
}

But isn't it breaking the Dependency Inversion Principle from SOLID? Another idea which is an extenstion of above is additional introduction of initialization method for TImpl and FImpl. Then I would provide implementation classes in the constructor and then do exact construction in the constructor body.

class Test {
    main() {
       P p = new PImpl(new GImpl(), new FImpl());
    }
}

abstract class P {
    G g;
    T t;
    F f;

    P(G g, T t, F f) {
        this.g = g;
        this.t = t.create(g);
        this.f = f.create(t);
    }
}

class PImpl extends P {
     
     PImpl(G g, F f) {
        super(g, new TImpl(), f);
     }
}

But I'm not sure if this brings any additional value and only makes the code more complex.

Aucun commentaire:

Enregistrer un commentaire