-
-
Save irfanandriansyah1997/ae9b7c7a0c76d015ed72eeb0b949ccf8 to your computer and use it in GitHub Desktop.
Dependency injection example in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class MySqlDb(object): | |
| def run(self, query): | |
| # whatever... | |
| # ---------------------------------------------------------------------- | |
| # Here, Foo can get bars, AND knows exactly what db implementation to use: | |
| class Foo: | |
| def __init__(self): | |
| self.db = MySqlDb() | |
| def get_bars(self): | |
| return self.db.run("select * from bars") | |
| foo = Foo() | |
| bars = foo.get_bars() | |
| # ---------------------------------------------------------------------- | |
| # Here, Foo can only get bars, you have to give it a db to use. | |
| # Makes it more flexible (and easier to test). | |
| class Foo: | |
| def __init__(self, db): | |
| self.db = db | |
| def get_bars(self): | |
| return self.db.run("select * from bars") | |
| db = MySqlDb() | |
| foo = Foo(db) | |
| bars = foo.get_bars() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment