【发布时间】:2017-12-12 08:49:41
【问题描述】:
在工厂设计中,当我使用工厂类创建新对象时,我会要求用户输入他/她的输入,然后在工厂类中从用户那里获取输入,然后使用这些输入创建对象。
在工厂类中获取用户输入是否可行? 我应该如何在工厂类中获取用户输入?
工厂类在下面;
Type *Factory::create_type(int Type){
switch(Type){
case 1:{
return new A(this->getUserTime(),this->getUserValue());
}
case 2:{
float min = this->getUserMin();
float max = this->getUserMax();
if(this->validMinMax(min,max))
return new B(this->getUserSpeed(),this >getUserValue(),min,max);
else
return NULL;
}
case 3:{
float min = this->getUserMin();
float max = this->getUserMax();
if(this->validUserMinMax(max,min))
return new C(this->getUserSpeed(),this->getUserValue(),max,min);
else
return NULL;
}
case 4:{
return new D(this->getUserDistance(),this->getUserSpeed(),this->getUserValue());
}
}}
工厂类的输入函数之一;
float Factory::getUserValue(){
float m;
std::cout<<"\n enter value:";
std::cin>>m
return m; }
【问题讨论】:
-
我建议您尝试提出一个不需要使用magic numbers 的实现。枚举是一种方式。继承另一个。模板和专业化是第三个。
-
首先,带着那个裸指针离开这里。使用
std::unique_ptr或std::shared_ptr。至于输入,实际上你在一个开关中只有 4 种不同的方法。我会将它们提取到单独的方法中,如果需要,创建另一个使用枚举来决定调用哪个方法的工厂或方法。我首选的解决方案是使用另一个工厂/类,因为您将“做什么”与“如何制造”分开。 -
@OscardeLeeuw 这些智能指针的唯一问题是:您将特定的使用权强加给用户 - 但他/她实际上可能需要另一个...当然,他/她可以接受out 并将其分配给其他类型,但在这种特定情况下,作为用户,我希望能够将裸指针直接分配给我需要使用的智能指针(我自己)。
标签: c++ object design-patterns user-input factory-pattern