How to do dependency injection in C
Dependency injection (DI) is a technique for achieving loose coupling between objects and their dependencies. In C, you can implement dependency injection using the following steps:
Create an interface for the dependency that will be injected. This interface should define the methods that the dependent object will use.
Create an implementation of the interface. This implementation will provide the actual functionality that the dependent object will use.
In the dependent object, define a member variable of the interface type. This variable will be used to hold a reference to the dependency.
In the dependent object's constructor, pass in an instance of the implementation as a parameter. Assign this instance to the member variable defined in step 3.
In the dependent object's methods, use the member variable to access the dependency's methods.
To change the dependency, pass a new instance of the implementation to the dependent object's constructor.
see code
// interface for the dependency typedef struct Dependency { void (*function)(); } Dependency; // implementation of the dependency typedef struct DependencyImpl { Dependency base; } DependencyImpl; void DependencyImpl_function(Dependency* base) { // implementation } DependencyImpl* DependencyImpl_new() { DependencyImpl* impl = malloc(sizeof(DependencyImpl)); impl->base.function = DependencyImpl_function; return impl; } // dependent object typedef struct Object { Dependency* dependency; } Object; Object* Object_new(Dependency* dependency) { Object* obj = malloc(sizeof(Object)); obj->dependency = dependency; return obj; } void Object_doSomething(Object* obj) { obj->dependency->function(); } int main() { DependencyImpl* impl = DependencyImpl_new(); Object* obj = Object_new((Dependency*)impl); Object_doSomething(obj); }
No comments:
Post a Comment