Dependency Injection for Procedural Programming

后端 未结 5 680
野性不改
野性不改 2021-02-13 23:00

Suppose I\'ve decided to write a large application in C, or any other procedural programming language. It has functions with call-dependencies that look like this:



        
5条回答
  •  时光说笑
    2021-02-13 23:41

    If you only require the DI for unit testing you may use the linker to do it.

    What I mean is that the functions B1 & B2 are declared in a header and used by function A, so the implementation of the B functions is provided by the linker. You just need to provide a different C-File for unit tests. This should not be a big problem, as you probably have your own makefile for the unit test anyhow.

    If you require dynamic dependency resolution at runtime you should use a factory pattern (a function returning the function-pointer) for function pointers and pull them from the factory when required. The factory may decide depending on global context what function to return.

提交回复
热议问题