The principle of dependency inversion in software

        In the software design mode, there is a Dependence Inversion Principle (DIP), which is more practical, and it is introduced below.
        1. The definition of the dependency inversion principle
        depends on abstraction (interface), not on specific implementation (class), that is, programming for interfaces.
        2. Case
        1.1 Original design ver1.1

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
using namespace std;

class Benz
{
    
    
public:
	void run(){
    
    
		cout << "奔驰开起来了";
	}
};

class BMW
{
    
    
public:
	void run(){
    
    
		cout << "BMW开起来了";
	}
};

class Zhang3
{
    
    
public:
	Zhang3(Benz *benz) {
    
    
		this->benz = benz;
	}

	void driveBenz() {
    
    
		benz->run();
	}

	void driveBMW() {
    
    
		bmw->run();
	}

private:
	Benz *benz;
	BMW  *bmw;
};



int main(void)
{
    
    
	Benz benz;
	Zhang3 zhang3(&benz);
	zhang3.driveBenz();

	return 0;
}

        1.2 Design ver1.2 with the principle of dependency inversion added

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
using namespace std;

//---------------- 抽象层 --------------------
class Car
{
    
    
public:
	virtual void run() = 0;
};

class Driver
{
    
    
public:
	virtual void drive() = 0;
};

//---------------- 实现层 --------------------
class Benz :public Car
{
    
    
public:
	virtual void run(){
    
    
		cout << "benz run..." << endl;
	}
};

class BMW :public Car
{
    
    
public:
	virtual void run(){
    
    
		cout << "BMW run..." << endl;
	}
};

class Zhang3 :public Driver
{
    
    
public:
	Zhang3(Car *car){
    
    
		this->car = car;
	}

	virtual void drive(){
    
    
		cout << "Zhang3开车了" << endl;
		car->run();
	}

	Car *car;
};

class Li4 :public Driver
{
    
    
public:
	Li4(Car *car){
    
    
		this->car = car;
	}

	virtual void drive(){
    
    
		cout << "Li4开车了" << endl;
		car->run();
	}

	Car *car;
};

//---------------- 业务逻辑层 --------------------
int main(void)
{
    
    

	//让Zhang3开奔驰
	Car *benz = new Benz;
	Driver *zhang3 = new Zhang3(benz);

	zhang3->drive();

	//让李4开宝马
	Car *bmw = new BMW;
	Driver *li4 = new Li4(bmw);
	li4->drive();

	return 0;
}

        Version ver1.2 has better maintainability and scalability than ver1.1 code.

Guess you like

Origin blog.csdn.net/sanqima/article/details/105328328