본문 바로가기
C++/0x01-design pattern

Factory Method

by SpeeDr00t 2016. 7. 18.
반응형

Factory Method

1.소스

#include <iostream>
#include <string>
#include <cstring>

using namespace std;


/* Abstract base class declared by framework */
class Document
{
public:
    Document(char *fn)
    {
        strcpy(name, fn);
    }
	
    virtual void Open() = 0;
    virtual void Close() = 0;
	
    char *GetName()
    {
        return name;
    }
	
private:
    char name[20];
};



/* Concrete derived class defined by client */
class MyDocument: public Document
{
public:
    MyDocument(char *fn): Document(fn){}
	
    void Open()
    {
        cout << "   MyDocument: Open()" << endl;
    }
	
    void Close()
    {
        cout << "   MyDocument: Close()" << endl;
    }
	
};



/* Framework declaration */
class Application
{
public:
    Application(): _index(0)
    {
        cout << "Application: ctor" << endl;
    }
	
    /* The client will call this "entry point" of the framework */
    void NewDocument(char *name)
    {
        cout << "Application: NewDocument()" << endl;
        /* Framework calls the "hole" reserved for client customization */
        _docs[_index] = CreateDocument(name);
        _docs[_index++]->Open();
    }
	
    void OpenDocument(){}
    void ReportDocs();
	
    /* Framework declares a "hole" for the client to customize */
    virtual Document *CreateDocument(char*) = 0;
	
	
private:
    int _index;
    /* Framework uses Document's base class */
    Document *_docs[10];
};

void Application::ReportDocs()
{
    cout << "Application: ReportDocs()" << endl;
	
    for (int i = 0; i < _index; i++) {
        cout << "   " << _docs[i]->GetName() << endl;
	}
}

/* Customization of framework defined by client */
class MyApplication: public Application
{
public:
    MyApplication()
    {
        cout << "MyApplication: ctor" << endl;
    }
	
    /* Client defines Framework's "hole" */
    Document *CreateDocument(char *fn)
    {
        cout << "   MyApplication: CreateDocument()" << endl;
        return new MyDocument(fn);
    }
};

int main()
{
    /* Client's customization of the Framework */
    MyApplication myApp;

    myApp.NewDocument( (char *)("foo") );
    myApp.NewDocument( (char *)("bar") );
    myApp.ReportDocs();
}

결과

g++ -o factory_method factory_method.cpp
hacker@HACKER:~/cpp$ ./factory_method
Application: ctor
MyApplication: ctor
Application: NewDocument()
   MyApplication: CreateDocument()
   MyDocument: Open()
Application: NewDocument()
   MyApplication: CreateDocument()
   MyDocument: Open()
Application: ReportDocs()
   foo
   bar
반응형

'C++ > 0x01-design pattern' 카테고리의 다른 글

Chain of Responsibility  (0) 2016.07.18
Prototype  (0) 2016.07.18
builder pattern  (0) 2016.07.18
proxy pattern  (0) 2016.07.18
Flyweight pattern  (0) 2016.07.18