最近在学习C++语言,想到了面向对象里面经常提到的两个概念:
- 面向接口而非面向实现编程;
- 依赖注入
故思考了下如何用C++的抽象类模拟抽象接口,利用其多态的特性来实现以上两点内容。 领域原型很简单: 高层逻辑SportsMeetingParticipater依赖于抽象接口Athlete; 该依赖以依赖注入的方式体现在SportsMeetingParticipater的代码中; 具体实现的类Cat、Dog依赖于Athlete; 从而达到高层逻辑SportsMeetingParticipater不依赖于具体实现Cat、Dog的效果。
具体代码如下:
#include<iostream>
using namespace std;
class Athlete
{
public:
virtual void run(void) = 0;
virtual void eat(void) = 0;
};
class Cat : public Athlete
{
public:
void run(void);
void eat(void);
};
class Dog : public Athlete
{
public:
void run(void);
void eat(void);
};
void Cat::run(void)
{
cout<<"The cat is runing for mouse!"<<endl;
};
void Cat::eat(void)
{
cout<<"The cat is eating fish!"<<endl;
};
void Dog::run(void)
{
cout<<"The dog is runing for chicken!"<<endl;
};
void Dog::eat(void)
{
cout<<"The dog is eating meat!"<<endl;
};
class SportsMeetingParticipater
{
private:
Athlete* athlete;
public:
SportsMeetingParticipater(Athlete& b)
{
this->athlete = &b;
}
void showUp(void)
{
this->athlete->run();
this->athlete->eat();
};
};
int main()
{
cout<<"CAT:"<<endl;
Cat cat;
SportsMeetingParticipater athlete_cat(cat);
athlete_cat.showUp();
cout<<"DOG:"<<endl;
Dog dog;
SportsMeetingParticipater athlete_dog(dog);
athlete_dog.showUp();
system("pause");
}
供以后回忆参考。
|