feat: implement AbstractFactory
This commit is contained in:
parent
d87b07f8d9
commit
149deafdb1
1 changed files with 56 additions and 0 deletions
|
@ -1,8 +1,64 @@
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
class Car {
|
||||||
|
public:
|
||||||
|
virtual ~Car() = default;
|
||||||
|
virtual std::string type() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class SportsCar : public Car {
|
||||||
|
public:
|
||||||
|
std::string type() const override { return "SportsCar"; }
|
||||||
|
};
|
||||||
|
class FamilyCar : public Car {
|
||||||
|
public:
|
||||||
|
std::string type() const override { return "FamilyCar"; }
|
||||||
|
};
|
||||||
|
|
||||||
|
class Truck {
|
||||||
|
public:
|
||||||
|
virtual ~Truck() = default;
|
||||||
|
virtual std::string type() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class SportsTruck : public Truck {
|
||||||
|
public:
|
||||||
|
std::string type() const override { return "SportsTruck"; }
|
||||||
|
};
|
||||||
|
class FamilyTruck : public Truck {
|
||||||
|
public:
|
||||||
|
std::string type() const override { return "FamilyTruck"; }
|
||||||
|
};
|
||||||
|
|
||||||
|
class VehicleFactory {
|
||||||
|
public:
|
||||||
|
virtual Car *createCar() const = 0;
|
||||||
|
virtual Truck *createTruck() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class SportsVehicleFactory : public VehicleFactory {
|
||||||
|
public:
|
||||||
|
Car *createCar() const override { return new SportsCar; }
|
||||||
|
Truck *createTruck() const override { return new SportsTruck; }
|
||||||
|
};
|
||||||
|
|
||||||
|
class FamilyVehicleFactory : public VehicleFactory {
|
||||||
|
public:
|
||||||
|
Car *createCar() const override { return new FamilyCar; }
|
||||||
|
Truck *createTruck() const override { return new FamilyTruck; }
|
||||||
|
};
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) {
|
||||||
|
|
||||||
std::cout << "AbstractFactory" << std::endl;
|
std::cout << "AbstractFactory" << std::endl;
|
||||||
|
|
||||||
|
auto sportsTruck =
|
||||||
|
std::unique_ptr<Truck>(SportsVehicleFactory().createTruck());
|
||||||
|
auto familyCar = std::unique_ptr<Car>(FamilyVehicleFactory().createCar());
|
||||||
|
|
||||||
|
std::cout << "I am a " << sportsTruck->type() << std::endl;
|
||||||
|
std::cout << "I am a " << familyCar->type() << std::endl;
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue