案例:制作饮品的步骤是差不多一样的,假设都有四步,打开包装Open、煮水Boil、放杯子里面PutInCup、放佐料PutSomething、喝Drink
利用多态,制作茶和咖啡等饮品
分析:定义一个抽象类,纯虚函数包括Open、Boil、PutInCup、PutSomething和Drink
茶和咖啡等饮品类去继承这个抽象类,并实现上述的纯虚函数
通过父类指针指向子类对象进行调用即可
#include<iostream>
class AbstractMakeDrinking
{
public:
virtual void Open() = 0;//打开包装
virtual void Boil() = 0;//煮开水
virtual void PutInCup() = 0;//放到杯子里面
virtual void PutSomething() = 0;//放调料
virtual void Drink() = 0;//喝饮料
void makeDrink()
{
Open();
Boil();
PutInCup();
PutSomething();
Drink();
}
};
class Tea :public AbstractMakeDrinking
{
void Open()
{
std::cout << "Open tea..." << std::endl;
}
void Boil()
{
std::cout << "Boil water..." << std::endl;
}
void PutInCup()
{
std::cout << "Put tea in cup..." << std::endl;
}
void PutSomething()
{
std::cout << "Put milk in cup..." << std::endl;
}
void Drink()
{
std::cout << "Drink tea..." << std::endl;
}
};
class Coffea :public AbstractMakeDrinking
{
void Open()
{
std::cout << "Open Coffea..." << std::endl;
}
void Boil()
{
std::cout << "Boil milk..." << std::endl;
}
void PutInCup()
{
std::cout << "Put Coffea in cup..." << std::endl;
}
void PutSomething()
{
std::cout << "Put sugar in cup..." << std::endl;
}
void Drink()
{
std::cout << "Drink Coffea..." << std::endl;
}
};
void doWork(AbstractMakeDrinking *makedrink) //AbstractMakeDrinking *makedrink = new xxx 父类指针makedrink指向子类对象xxx
{
makedrink->makeDrink();
delete makedrink;
}
int main(int argc,char ** agrv)
{
Tea *tea = new Tea;
doWork(tea);
std::cout << "-------------------" << std::endl;
doWork(new Coffea);
return 0;
}
运行效果: