标签: factory-method

工厂方法反执行

我正在我的C++项目中应用Factory设计模式,下面你可以看到我是如何做到的.我尝试通过遵循"反if"活动来改进我的代码,因此想要删除我所拥有的if语句.不知道怎么办呢?

typedef std::map<std::string, Chip*> ChipList;

Chip* ChipFactory::createChip(const std::string& type) {
    MCList::iterator existing = Chips.find(type);
    if (existing != Chips.end()) {
        return (existing->second);
    }
    if (type == "R500") {
        return Chips[type] = new ChipR500();
    }
    if (type == "PIC32F42") {
        return Chips[type] = new ChipPIC32F42();
    }
    if (type == "34HC22") {
        return Chips[type] = new Chip34HC22();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我会想象创建一个以字符串为键的映射,以及构造函数(或创建对象的东西).之后,我可以使用类型(类型是字符串)从地图中获取构造函数并创建我的对象而不使用任何if.(我知道我有点偏执,但我想知道它是否可以完成.)

c++ factory-method

1
推荐指数
2
解决办法
2702
查看次数

java参数化通用静态工厂

在Java中是否可以创建一个静态工厂方法/类,它使用接口作为参数化类型并返回给定接口的实现类?

虽然我对泛型的了解有限,但这就是我想要做的:

// define a base interface:
public interface Tool {
    // nothing here, just the interface.
}

// define a parser tool:
public interface Parser extends Tool {
    public ParseObject parse(InputStream is); 
}

// define a converter tool:
public interface Converter extends Tool {
    public ConvertObject convert(InputStream is, OutputStream os);
}

// define a factory class
public class ToolFactory {
    public static <? extends Tool> getInstance(<? extends Tool> tool) {
       // what I want this method to return is: …
Run Code Online (Sandbox Code Playgroud)

java generics design-patterns factory factory-method

1
推荐指数
1
解决办法
5888
查看次数

抽象工厂与工厂方法:构成与实力?

我已经阅读了很多关于抽象工厂和工厂方法之间不同的帖子,但是有一个我无法理解的问题.

两者之间的一个区别是,使用抽象工厂模式,类通过组合将对象实例化的责任委托给另一个对象,而工厂方法模式使用继承并依赖子类来处理所需的对象实例化

也许我知道为什么抽象工厂模式使用组合和委托创建对象,但我无法理解为什么工厂方法模式使用继承来创建具体的类对象.

design-patterns factory-method abstract-factory

1
推荐指数
1
解决办法
1648
查看次数

C#中的工厂方法模式

class A实现IC
class B工具IC

class Factory有方法GetObject(int x); x=0因为A,x=1B.

我如何可以强制的使用Factory.GetObject方法来创建类型的对象A,并B防止类似new A(),这应该是Factory.GetObject(0)

c# factory-method

0
推荐指数
1
解决办法
2857
查看次数

解除引用这会导致分段错误

我有以下功能

LinearScheme::LinearScheme() {
    cout << " empty constructor" << endl;
}


void LinearScheme::init(
    int tableId,
    std::string &basePath,
    std::vector<size_t> &colElemSizes,
    TupleDescMap &tupleDescMap,
    size_t defaultMaxFragmentSize,
    int numCols,
    BoundBases &bounds,
    std::vector<int> &colsPartitioned ) 
{
    // This linear scheme ignores bounds
    // it could be improved to use colsPartitioned for ordering (TODO)
    cout << "init Linear Scheme " << endl;

    *this = LinearScheme(); //SEGFAULTS HERE

    cout << "after cons here?" << endl;
    // init private fields    
    this->tableId_ = tableId;
    this->basePath_ = basePath;
    this->colElemSizes_ = …
Run Code Online (Sandbox Code Playgroud)

c++ constructor factory-method segmentation-fault

-1
推荐指数
1
解决办法
381
查看次数