【问题标题】:Abstract Factory Pattern Client Code抽象工厂模式客户端代码
【发布时间】:2013-11-26 10:18:18
【问题描述】:

我正在尝试为 abs 工厂编写我的客户端代码,但我被困在客户端代码中。我无法通过Factorymaker.getFactory("Bshell"); 实例化任何 Bshell 代码在没有客户端代码的情况下编译

(我是stackoverflow的新手。我的iostream在我的代码中是正常的。)

#include <iostream> 

using namespace std;
//This is the abstract product.
class Shell {

public:
    virtual void printShell(){ cout << "I am the abstract product\n"; }
};
class Bshell : public Shell {

public:
    Bshell();
    Bshell(string arg){ cout << "I am " << arg << endl; }
    void printShell(){ cout << "I am Bshell\n"; }
};
class Cshell : public Shell {

public:
    Cshell();
    Cshell(string arg){ cout << "I am " << arg << endl; }
    void printShell(){ cout << "I am Cshell\n"; }
};
class Kshell : public Shell {

public:
    Kshell();
    Kshell(string arg){ cout << "I am " << arg << endl; }
    void printShell(){ cout << "I am Kshell\n"; }
};
//This is the abstract factory.
class ShellFactory {

public:
    virtual Shell* createBshell();
    virtual Shell* createCshell();
    virtual Shell* createKshell();
};
//Concrete factories
class BShellFactory : public ShellFactory {

public:
    Shell* createBshell(){ return new Bshell("Bshell"); }
};
class CShellFactory : public ShellFactory {

public:
    Shell* createCshell(){ return new Cshell("Cshell"); }
};
class KShellFactory : public ShellFactory {

public:
    Shell* createKshell(){ return new Kshell("Kshell"); }
};
//indirectly instantiating factories
class Factorymaker {

private:
    ShellFactory *sf = NULL;
public:
    ShellFactory* getFactory(string choice){

        if (choice == "Bshell"){ sf = new BShellFactory(); }
        else if (choice == "Cshell"){ sf = new CShellFactory(); }
        else if (choice == "Kshell"){ sf = new KShellFactory(); }
        return this->sf;
    }
};
int main()
{
    Factorymaker *fmaker = new Factorymaker();
    ShellFactory *sf = fmaker.getFactory("Bshell");
    Bshell bshellproduct = sf.createBshell();
    return 0;
}

【问题讨论】:

    标签: c++ design-patterns factory abstract


    【解决方案1】:

    fmakersf 是指针,所以使用-&gt; 而不是. 来访问它们的成员。

    sf-&gt;createBshell()的返回类型是Shell*,所以应该是bshellproduct的类型。

    你的编译器应该已经告诉你所有这些了。

    【讨论】:

    • 谢谢!我的编译器说,未定义引用 vtable for ShellFactory' undefined reference to ShellFactory::createBshell()' 未定义引用 `typeinfo for ShellFactory'
      Factorymaker fmaker = new Factorymaker(); ShellFactory *sf = fmaker->getFactory("Bshell");壳 bshel​​lproduct = sf->createBshell();
    • @SinanTalebi:那是因为您在ShellFactory 基类中声明了三个纯函数,并且在每个具体工厂中只覆盖了一个。您可能应该将接口更改为单个 create() 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多