工廠模式
Before
cpp
struct InputContainer {
std::shared_ptr<Input> insertInput(const std::string& name) {
std::shared_ptr<Input> obj;
if (name == "button") {
obj = std::make_shared<Button>();
} else if (name == "checkedbox") {
obj = std::make_shared<Checkbox>();
} else {
throw std::runtime_error("`" + name + "` is not a input Component");
}
obj.bindParent(this);
// ... more pre op on obj
return obj;
}
};
可以發現 if-else-branch 那段是「會需要修改的」,所以需要把他拔出。
使用者:難道我想新增一種 input component 的話要自己去改 code??
cpp
struct InputContainer {
InputContainer() = default;
virtual ~InputContainer() = default;
std::shared_ptr<Input> insertInput(const std::string& name) {
auto obj = createInput(name);
obj.bindParent(this);
// ... more pre op on obj
return obj;
}
// implement a default factory
virtual std::shared_ptr<Input> createInput(const std::string& name) const {
std::shared_ptr<Input> obj;
if (name == "button") {
obj = std::make_shared<Button>();
} else if (name == "checkedbox") {
obj = std::make_shared<Checkbox>();
} else {
throw std::runtime_error("`" + name + "` is not a input Component");
}
}
};