抽象工厂与工厂模式的联系与区别:
工厂模式:要么生产香蕉、要么生产苹果、要么生产西红柿;但是不能同时生产一
个产品组。
抽象工厂:能同时生产一个产品族。===》抽象工厂存在原因
解释:具体工厂在开闭原则下, 能生产香蕉/苹果/梨子; (产品等级结构)
抽象工厂:在开闭原则下, 能生产:南方香蕉/苹果/梨子 (产品族)北方香蕉/苹果/梨子
重要区别:
工厂模式只能生产一个产品。(要么香蕉、要么苹果)
抽象工厂可以一下生产一个产品族(里面有很多产品组成)
class Fruit {
public:
virtual void getFruitName() = 0;
};
class FruitFactory {
public:
virtual Fruit* getApple() = 0;
virtual Fruit* getGrape() = 0;
};
class SouthApple :public Fruit {
public:
void getFruitName() {
cout << "SouthApple-----------------" << endl;
}
};
class SouthGrape:public Fruit{
public:
void getFruitName() {
cout << "SouthGrape-----------------" << endl;
}
};
class NorthApple :public Fruit {
public:
void getFruitName() {
cout << "NorthApple-----------------" << endl;
}
};
class NorthGrape :public Fruit {
public:
void getFruitName() {
cout << "NorthGrape-----------------" << endl;
}
};
class SouthFactory :public FruitFactory {
public:
Fruit* getApple() {
return new SouthApple;
}
Fruit* getGrape() {
return new SouthGrape;
}
};
class NorthFactory :public FruitFactory {
public:
Fruit* getApple() {
return new NorthApple;
}
Fruit* getGrape() {
return new NorthGrape;
}
};
int main() {
FruitFactory* fa = NULL;
Fruit* fu = NULL;
fa = new SouthFactory;
fu = fa->getApple();
fu->getFruitName();
fu = fa->getGrape();
fu->getFruitName();
delete fu;
delete fa;
system("pause");
return 0;
}