设计模式(C++) 练习1 简单工厂模式
Design Patterns(C++) Exercise 1:Easy Factory Model
Exercise 1.1
一个农场专门负责种植各种水果,比如苹果、草莓、葡萄等,任何水果都可以种植、生长和采摘.此外,每一种水果还有自己的特性,如:苹果是多年生具有树龄的属性,葡萄则分为有籽或无籽等。农场生产的水果都送入超市进行销售。请采用简单工厂模式对上述问题进行建模,要求画出类图并使用C++语言编写程序。
/**
* @author 墨晓柯
*/
#include<iostream>
#define interface class
using namespace std;
interface IFruit {
public:
virtual void plant() = 0;
virtual void grow() = 0;
virtual void harvest() = 0;
};
class Apple : public IFruit{
private:
int treeAge;
public:
void setTreeAge(int aTreeAge) {
treeAge = aTreeAge;
}
int getTreeAge() {
return treeAge;
}
void plant() {
cout << "Apple planted!" << endl;
}
void grow() {
cout << "Apple growing!" << endl;
}
void harvest() {
cout << "Apple harvested!" << endl;
}
};
class Strawberry : public IFruit {
public:
void plant() {
cout << "Strawberry planted!" << endl;
}