Compare commits

...

2 Commits

Author SHA1 Message Date
149deafdb1
feat: implement AbstractFactory 2024-03-14 14:27:11 +01:00
d87b07f8d9
chore: add AbstractFactory 2024-03-14 14:10:17 +01:00
4 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,21 @@
cmake_minimum_required(VERSION 3.20)
project(
AbstractFactory
VERSION 0.1.0
LANGUAGES CXX)
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/../cmake")
include(ExportCompileCommands)
include(sccache)
add_executable(AbstractFactory main.cpp)
target_compile_features(AbstractFactory PUBLIC cxx_std_20)
set_target_properties(
AbstractFactory
PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/bin"
RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/bin"
RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/bin")

4
AbstractFactory/bootstrap.sh Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env sh
cmake -S . -B .build -G Ninja -D CMAKE_EXPORT_COMPILE_COMMANDS=ON
ln -s .build/compile_commands.json

3
AbstractFactory/build.sh Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env sh
cmake --build .build

64
AbstractFactory/main.cpp Normal file
View File

@ -0,0 +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;
}