C++多态的设计套路

第一部分:正常的多态继承
#include <iostream>
using namespace std;

class People {
public:
	void eat() {
		get_util_to_eat();
	}

	virtual void get_util_to_eat() {
		std::cout << "People get chopsticks" << std::endl;
	}
};

class Children : public People {
public:
	virtual void get_util_to_eat() {
		std::cout << "Children get scoop" << std::endl;
	}
};

int main() {
	People* people = new Children();
	people->eat();
	return 0;
}


在基类中使用子类的方法 
这是非常常见的程序设计
我们一般是抽象一个基类 这个基类是放在中间位置的
往下是硬件的派生
往上是业务的派生
硬件/业务都是基于抽象类来操作的
就想门禁机里面上面MQTT下面W5500/SIM800C中间用一个socket隔离的



设计思路:
A---最开始 妈妈 直接 操作 书本  这样就是耦合度比较高的 书本换成杂志 你就蒙蔽了
开始A
#include <iostream>
#include <string>
using namespace std;

class Book {
public:
	string getContents() { return "听妈妈讲故事-BOOK\r\n"; };

};

class Mother{
public:
	void tellStory(Book *b) { cout << b->getContents() << endl; };
};


int main() {
	Mother mother;
	Book *b = new Book;
	mother.tellStory(b);
	system("pause");
	return 0;
}

B--加入杂志 妈妈 怎么操作杂志呢?
#include <iostream>
#include <string>
using namespace std;

class Book {
public:
	string getContents() { return "听妈妈讲故事-BOOK\r\n"; };

};
class Ebook {
public:
	string getContents() { return "听妈妈讲故事-EbOOK\r\n"; };

};

class Mother{
public:
	void tellStory(Book *b) { cout << b->getContents() << endl; };
	void tellStory(Ebook *eb) { cout << eb->getContents() << endl; };
};


int main() {
	Mother mother;
	Ebook *eb = new Ebook;
	mother.tellStory(eb);
	system("pause");
	return 0;
}

看到我需要修改 Mother 了 这样不好!
怎么办?抽象
Mother 操作的是一个抽象的类  其他的书籍 杂志什么的 去实现抽象类 派生出去重写

#include <iostream>
#include <string>
using namespace std;

class Base {
public:
	virtual string getContents() = 0;
};

class Book :public Base {
public:
	virtual string getContents() override { return "听妈妈讲故事-BOOK\r\n"; };

};
class Ebook :public Base {
public:
	virtual string getContents() override { return "听妈妈讲故事-EbOOK\r\n"; };

};

class Mother{
public:
	void tellStory(Base *b) { cout << b->getContents() << endl; };
};


int main() {
	Mother mother;
	Ebook *eb = new Ebook;
	Book  *b  = new Book;
	mother.tellStory(eb);
	mother.tellStory(b);
	delete b;
	delete eb;
	system("pause");
	return 0;
}


高层模块不依赖底层模块
高层底层都依赖其抽象层
抽象不依赖细节
细节应依赖抽象

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值