CppPatterns/AbstractFactory/main.cpp

65 lines
1.5 KiB
C++
Raw Permalink Normal View History

2024-03-14 13:10:17 +00:00
#include <iostream>
2024-03-14 13:27:11 +00:00
#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; }
};
2024-03-14 13:10:17 +00:00
int main(int argc, char *argv[]) {
std::cout << "AbstractFactory" << std::endl;
2024-03-14 13:27:11 +00:00
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;
2024-03-14 13:10:17 +00:00
return EXIT_SUCCESS;
}