C++ 抽象工厂模式

内容目录
#include <iostream>

class IElevator {
public:
    virtual void goToFloor(int floor) = 0; // Pure virtual function
    virtual ~IElevator() {} // Virtual destructor
};

class SupplierAElevator : public IElevator {
public:
    void goToFloor(int floor) override {
        std::cout << "SupplierA's elevator is moving to floor " << floor << std::endl;
    }
};

class SupplierBElevator : public IElevator {
public:
    void goToFloor(int floor) override {
        std::cout << "SupplierB's elevator is moving to floor " << floor << std::endl;
    }
};

class IElevatorFactory {
public:
    virtual IElevator* createElevator() = 0; // Pure virtual function
    virtual ~IElevatorFactory() {} // Virtual destructor
};

class SupplierAFactory : public IElevatorFactory {
public:
    IElevator* createElevator() override {
        return new SupplierAElevator();
    }
};

class SupplierBFactory : public IElevatorFactory {
public:
    IElevator* createElevator() override {
        return new SupplierBElevator();
    }
};

int main() {
    // 创建电梯工厂
    IElevatorFactory* factoryA = new SupplierAFactory();
    IElevatorFactory* factoryB = new SupplierBFactory();

    // 创建电梯
    IElevator* elevatorA = factoryA->createElevator();
    IElevator* elevatorB = factoryB->createElevator();

    // 电梯运行
    elevatorA->goToFloor(10);
    elevatorB->goToFloor(20);

    // 收尾
    delete elevatorA;
    delete elevatorB;
    delete factoryA;
    delete factoryB;

    return 0;
}
打赏作者