c++ - 抽象工厂模式客户端代码

标签 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;
}

最佳答案

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

sf->createBshell()的返回类型是Shell*,所以应该是bshel​​lproduct的类型。

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

关于c++ - 抽象工厂模式客户端代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214179/

相关文章:

c++ - std string对象的内部结构

design-patterns - "TryParse/Parse like"模式 : what is the best way to implement it

javascript - 原型(prototype)模式,在 jQuery $.each 函数中使用 'this'

laravel-5 - 如何使用 $faker->word 获得独特的值(value)?

c++ - 在 C++ 中使用字符串末尾的整数值对字符串 vector 进行排序

c++ - 未定义模板 “std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator<char>>”的隐式实例化

C++ 和 mktime : 26/6/1943 and 27/6/1943 are the same day

c++ - C++ 中的线程安全单例实现

kotlin - Kotlin-可扩展的类型安全的构建器

c++ - 静态本地数据的延迟初始化