23種設計模式之抽象工廠模式(建立型,2 AbstractFactory,c++實現)
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
usingnamespace std;
classFruit {
public:
virtual void sayName() = 0;
};
classSouthBanana :publicFruit {
public:
void sayName() {
cout <<"I am south banana"<< endl;
}
};
classNorthBanana :publicFruit {
public:
void sayName() {
cout <<
"I am north banana"<< endl;}
};
classSouthApple :publicFruit {
public:
void sayName() {
cout <<"I am south apple"<< endl;
}
};
classNorthApple :publicFruit {
public:
void sayName() {
cout <<"I am north apple"<< endl;
}
};
classAbstractFactory {
public:
virtual Fruit *createBanana() = 0;
virtual Fruit *createApple() = 0;
};
classSouthFactory :publicAbstractFactory {
public:
Fruit *createBanana() {
returnnewSouthBanana;
}
Fruit *createApple() {
returnnewSouthApple;
}
};
classNorthFactory :publicAbstractFactory {
public:
Fruit *createBanana() {
returnnewNorthBanana;
}
Fruit *createApple() {
returnnewNorthApple;
}
};
void main() {
AbstractFactory*f = NULL;
Fruit*fruit = NULL;
f = newSouthFactory;
fruit = f->createBanana();
fruit->sayName();
delete fruit;
fruit = f->createApple();
fruit->sayName();
delete fruit;
delete f;
f = newNorthFactory;
fruit = f->createBanana();
fruit->sayName();
delete fruit;
fruit = f->createApple();
fruit->sayName();
delete fruit;
delete f;
}