- Expert Android Programming
- Prajyot Mainkar
- 295字
- 2021-07-08 10:29:15
Dependency Inversion Principle
The Dependency Inversion Principle states that:
1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
2. Abstractions should not depend upon details. Details should depend upon abstractions.
The best way to explain this principle is by giving an example. Let's assume we have a worker class that is a low level class and a Manager class that is a high level class. The Manager class contains many complex functionalities which it implements along with the Worker class, so the classes will look something like this:
class Worker { public void work() { // ....working } } class Manager { //--Other Functionality Worker worker; public void setWorker(Worker w) { worker = w; } public void manage() { worker.work(); } }
Here the Manager class has been implemented and is directly associated with the Worker class due to which changes in the Worker class directly affect the Manager class.
If we have to add another class which would be a parent of the Worker class, and the Worker class does similar work to that of the Manager class, it will require lots of changes.
To make it easier to add the Manager class, we will use interfaces:
interface IWorker { public void work(); } class Worker implements IWorker{ public void work() { // ....working } } class SuperWorker implements IWorker{ public void work() { //.... working much more } } class Manager { IWorker worker; public void setWorker(IWorker w) { worker = w; } public void manage() { worker.work(); } }
Now the both the worker and SuperWorker class implement the IWorker, while the Manager class directly uses the IWorker to complete its functionality by which changes to the Worker and SuperWorker do not affect the Manager class.
- The Modern C++ Challenge
- LabVIEW程序設計基礎與應用
- Oracle從新手到高手
- Microsoft Dynamics 365 Extensions Cookbook
- Magento 2 Theme Design(Second Edition)
- Backbone.js Blueprints
- 從Excel到Python:用Python輕松處理Excel數據(第2版)
- ExtJS高級程序設計
- 小程序,巧應用:微信小程序開發實戰(第2版)
- SQL Server 2008 R2數據庫技術及應用(第3版)
- MongoDB Cookbook(Second Edition)
- Java并發實現原理:JDK源碼剖析
- 深入理解Kafka:核心設計與實踐原理
- Visual C++程序設計全程指南
- Moodle 3.x Developer's Guide