抽象工廠模式提供一個介面來建立相關或相依的物件家族,而不需要指定具體類別
Head First Design Patterns, 2nd (p.156)
// 車型
enum class CarType {
MICRO, MINI, LUXURY
};
// 產地
enum class Location {
DEFAULT, USA, INDIA
};
// 抽象車輛類
class Car {
public:
Car(CarType model, Location location) : model(model), location(location) {}
virtual void construct() = 0;
std::string getModel() {
return (model == CarType::MICRO) ? "MICRO" : (model == CarType::MINI) ? "MINI" : "LUXURY";
}
std::string getLocation() {
return (location == Location::DEFAULT) ? "DEFAULT" : (location == Location::USA) ? "USA" : "INDIA";
}
virtual ~Car() {}
protected:
CarType model;
Location location;
};
class LuxuryCar : public Car {
public:
LuxuryCar(Location location) : Car(CarType::LUXURY, location) {
construct();
}
void construct() override {
std::cout << "Connecting to luxury car" << std::endl;
}
};
class MicroCar : public Car {
public:
MicroCar(Location location) : Car(CarType::MICRO, location) {
construct();
}
void construct() override {
std::cout << "Connecting to Micro Car" << std::endl;
}
};
class MiniCar : public Car {
public:
MiniCar(Location location) : Car(CarType::MINI, location) {
construct();
}
void construct() override {
std::cout << "Connecting to Mini car" << std::endl;
}
};
class CarFactory {
public:
static Car* buildCar(CarType type) {
Car* car = nullptr;
Location location = Location::INDIA;
switch (location) {
case Location::USA:
car = USACarFactory::buildCar(type);
break;
case Location::INDIA:
car = INDIACarFactory::buildCar(type);
break;
default:
car = DefaultCarFactory::buildCar(type);
}
return car;
}
private:
class USACarFactory {
public:
static Car* buildCar(CarType model) {
Car* car = nullptr;
switch (model) {
case CarType::MICRO:
car = new MicroCar(Location::USA);
break;
case CarType::MINI:
car = new MiniCar(Location::USA);
break;
case CarType::LUXURY:
car = new LuxuryCar(Location::USA);
break;
}
return car;
}
};
class INDIACarFactory {
public:
static Car* buildCar(CarType model) {
Car* car = nullptr;
switch (model) {
case CarType::MICRO:
car = new MicroCar(Location::INDIA);
break;
case CarType::MINI:
car = new MiniCar(Location::INDIA);
break;
case CarType::LUXURY:
car = new LuxuryCar(Location::INDIA);
break;
}
return car;
}
};
class DefaultCarFactory {
public:
static Car* buildCar(CarType model) {
Car* car = nullptr;
switch (model) {
case CarType::MICRO:
car = new MicroCar(Location::DEFAULT);
break;
case CarType::MINI:
car = new MiniCar(Location::DEFAULT);
break;
case CarType::LUXURY:
car = new LuxuryCar(Location::DEFAULT);
break;
}
return car;
}
};
};
int main() {
Car* car1 = CarFactory::buildCar(CarType::MICRO);
Car* car2 = CarFactory::buildCar(CarType::MINI);
Car* car3 = CarFactory::buildCar(CarType::LUXURY);
}
[1]. https://skyyen999.gitbooks.io/-study-design-pattern-in-java/content/abstractFactory1.html
[2]. https://www.geeksforgeeks.org/abstract-factory-pattern/