If Singletons are bad then why is a Service Container good?

后端 未结 5 1536
太阳男子
太阳男子 2020-11-28 19:45

We all know how bad Singletons are because they hide dependencies and for other reasons.

But in a framework, there could be many objects that need t

5条回答
  •  日久生厌
    2020-11-28 20:21

    Because you can easily replace objects in Service Container by
    1) inheritance (Object Manager class can be inherited and methods can be overriden)
    2) changing configuration (in case with Symfony)

    And, Singletons are bad not only because of high coupling, but because they are _Single_tons. It's wrong architecture for almost all kinds of objects.

    With 'pure' DI (in constructors) you will pay very big price - all objects should be created before be passed in constructor. It will mean more used memory and less performance. Also, not always object can be just created and passed in constructor - chain of dependencies can be created... My English are not good enough to discuss about that completely, read about it in Symfony documentation.

提交回复
热议问题