#include <iostream>
#include <memory>
class Phone {
public:
virtual void call() = 0;
};
class HuaweiPhone : public Phone {
public:
void call() override {
std::cout << "Using Huawei Phone to make a call" << std::endl;
}
};
class ApplePhone : public Phone {
public:
void call() override {
std::cout << "Using Apple Phone to make a call" << std::endl;
}
};
class PhoneFactory {
public:
virtual std::unique_ptr<Phone> createPhone() = 0;
};
class HuaweiPhoneFactory : public PhoneFactory {
public:
std::unique_ptr<Phone> createPhone() override {
return std::make_unique<HuaweiPhone>();
}
};
class ApplePhoneFactory : public PhoneFactory {
public:
std::unique_ptr<Phone> createPhone() override {
return std::make_unique<ApplePhone>();
}
};
int main() {
std::unique_ptr<PhoneFactory> huaweiFactory = std::make_unique<HuaweiPhoneFactory>();
std::unique_ptr<Phone> huaweiPhone = huaweiFactory->createPhone();
huaweiPhone->call();
std::unique_ptr<PhoneFactory> appleFactory = std::make_unique<ApplePhoneFactory>();
std::unique_ptr<Phone> applePhone = appleFactory->createPhone();
applePhone->call();
return 0;
}
【C++】【设计模式】工厂方法模式
最新推荐文章于 2024-07-25 17:57:45 发布