抽象工厂模式客户端代码

时间:2013-11-26 10:18:18

标签: c++ design-patterns factory abstract

我正在尝试为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;
}

1 个答案:

答案 0 :(得分:1)

fmakersf是指针,因此请使用->而不是.来访问其成员。

sf->createBshell()的返回类型为Shell*,因此应该是bshellproduct的类型。

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