feat: implement AbstractFactory

This commit is contained in:
Michael Mandl 2024-03-14 14:27:11 +01:00
parent d87b07f8d9
commit 149deafdb1
Signed by: mandlm
GPG key ID: 4AA25D647AA54CC7

View file

@ -1,8 +1,64 @@
#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[]) {
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;
}