Creating Interdependent Objects

I have a design problem. I can not find a clean and pleasant solution. I am developing in PHP, but I believe that this can happen in any language. My main problem is that I have two objects that have circular interdependence at some level of indirection. This means that I have a class (name it F) that implements the Facade template, which contains an object (of class B) that itself needs to create a class of class A. For the constructor of class A, you need a facade F that must be created => Y me there is a circular interdependence of objects.

I believe that I cannot resolve circular interdependence (objects basically implement a state machine with a loop using a state template), so I'm looking for a clean solution. I myself came up with two possible solutions, but I don’t think they are particularly elegant:

  • Ask class A to implement the setFacade (F $ facace) method and remove the entire facade from the constructor and just set it after A and create the facade. Class A objects cannot work without a facade, so this will actually create a Class A object that cannot do anything until setFacade is called, and this will reduce encapsulation and allow replacing the facade with the runtime of the object, which I also like.

  • Embed something like a promise that is passed to A instead of a facade that can later resolve it as soon as it is created. I don’t want to introduce this additional layer of indirection, especially because I don’t have a good place to actually resolve the promise, than in methods that process the logic of logic inside A, which can: a) produce terrible errors and (more importantly) b) I need to check whether the promise has already been resolved or whether I will need to resolve it now, whenever the buisness logic is called. This is just a scary design in my eyes.

So, if anyone can come up with a better solution or can support one of my possible solutions with a good argument, I would be very happy.

+3
3

- , , . ( . , .)

, : , , , .., . , . ( , .)

, , ( ).

+2

, , ( , API), "" ( ) , . , , , B A, .

+1

, , , .

, , , , .

, , , . , , . , , , .

, .

+1

Source: https://habr.com/ru/post/1758542/


All Articles