我现在正在研究 OOD 的概念,并且我为一家披萨店创建了一个程序。这里的基类是披萨。我想把披萨的辣特征作为一个接口,但是在实际应用中发现一个问题。这是代码。我如何才能将披萨与辣结合起来?
我如何制作牛肉辣披萨对象[我如何制作披萨并通过界面使其变得辣]
如何使用界面在这里。
#include <iostream>
#include <string>
using namespace std;
// base-class
class Pizza
{
private:
void MakeDough()
{
cout << "Make " << getPizzaType() << " Pizza Dough is Done.." << endl;
}
void Bake()
{
cout << "Bake " << getPizzaType() << " Pizza is Done.." << endl;
}
void AddToppings()
{
cout << "Adding " << PizzaToppings() << " is Done.." << endl;
}
protected:
virtual string getPizzaType() = 0;
virtual string PizzaToppings() = 0;
public:
void MakePizza()
{
MakeDough();
AddToppings();
Bake();
cout << "======================================\n";
cout << getPizzaType() << " Pizza is Done..\n" << endl;
}
};
//interface
class Spicy
{
public:
virtual void makePizzaSpicy() = 0;
};
class BeefPizza : public Pizza, public Spicy
{
protected:
// from Pizza Class
virtual string getPizzaType()
{
return "Beef";
}
virtual string PizzaToppings()
{
return "Beef Pizza Toppings";
}
public:
// from spicy class
virtual void makePizzaSpicy()
{
// code
}
};
class ChickenPizza : public Pizza
{
protected:
virtual string getPizzaType()
{
return "Chicken";
}
virtual string PizzaToppings()
{
return "Chicken Pizza Toppings";
}
};
class MakingPizza
{
public:
void MakePizza(Pizza* pizza)
{
pizza->MakePizza();
}
};
int main()
{
// here how i can make beef spicy pizza object
}
接口应该描述如何使用对象,而不是对象如何工作,
例如,披萨类可以添加抽象
Spice
,并且您的披萨将定义 Spice
的工作方式。
class Spice
{
public:
virtual int GetSpiceValue() = 0;
};
class Pizza
{
public:
virtual void AddSpice(Spice& spice)
{
spice_level += spice.GetSpiceValue();
}
private:
int spice_level;
};
现在我可以实现
Chilli
,这是一个 Spice
并使用它。
class Chilli : public Spice
{
public:
int GetSpiceValue() override { return 5; }
};
int main()
{
Pizza pizza;
Chilli chilli;
pizza.AddSpice(chilli);
}
现在你的披萨不能是一个
Spicey
对象,因为 Spicey
并不能描述其他人将如何使用它,相反它可以是带有 Edible
方法的 Eat
。
class Edible
{
public:
virtual int Eat() = 0;
};
class Pizza : public Edible
{
public:
int Eat() override { return spice_level; }
void AddSpice(Spice& spice)
{
spice_level += spice.GetSpiceValue();
}
private:
int spice_level;
};
现在在我的餐厅里,我可以为人们提供
Edible
他们可以 Eat
的食物,但他们也可以选择他们的 Spice
。
class Diner
{
public:
void SetSpice(Spice* spice) { spice_order = spice; }
std::unique_ptr<Edible> ServeFood() {
auto item = std::make_unique<Pizza>();
item->AddSpice(*spice_order);
return item;
}
private:
Spice* spice_order;
};