Guide to write a 2D game engine (4)
2018-01-18If you take a look at the code so far, you will find out a big problem that every component in our game engine is isolated and cannot communicate with each other. In this article, we will try to introduce DI (Dependency Injection) pattern to our game engine framework.
What is DI?
First let us try to think about a very common scenario: you are writing class A, in which there is a method that is depending on another method in class B. What you write will be like this:
Then the problem is how could we get the instance of B? We can either create a B() or inject an instance of B.
The first one is considered not good enough since:
You may not create an instance of B without other dependencies. B may be depending on C, D, E or something else.
It is hard to test since you cannot tell the bugs are inside A or B.
Although the second one is better and it is widely used in modern software architecture, it won't fit in our system. Let us take snake game for example. In this game, we hav ...