设计模式观后(c++还原之二 依赖的信用)

依赖的信用



//言而无信,高低层依赖模块
class ICar {
public:
	virtual void run() {
		cout << "car run!";
	}
};

class Benz : public ICar {
public:
	virtual void run() {
		cout << "benz run";
	}
};

class BMW : public ICar {
public:
	virtual void run() {
		cout << "bmw run";
	}
};
//司机, 并非所有司机能开车,为了避免这种言而无信的情况
//专门写个类,用于继承。如此他们的依赖是可信的
class IDriver
{
public:
	virtual void drive(ICar* car);
};

class Driver : public IDriver {
public:
	virtual void drive(ICar* car) {
		//为了添加依赖,做run
		car->run();
		cout << "driver car";
	}
};

class Client {
public:
	void dmain() {
		IDriver* wang = new Driver;
		ICar* benz = new Benz;
		wang->drive(benz);
	}
};


你可能感兴趣的:(生活)