動態創建對象


回顧前面的文章,實現了一個簡單工廠模式來創建不同類對象,但由於c++沒有類似new "Circle"之類的語法,導致數中需要不斷地ifelse地去判斷,如果有多個不同類對象需要創建,顯然這是很費神的,下面通過宏定義注冊的方法來實現動態創建對象

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 
#ifndef _SHAPE_H_
#define _SHAPE_H_

class Shape
{
public:
    virtual void Draw() = 0;
    virtual ~Shape() {}
};

class Circle : public Shape
{
public:
    void Draw();
    ~Circle();
};

class Square : public Shape
{
public:
    void Draw();
    ~Square();
};

class Rectangle : public Shape
{
public:
    void Draw();
    ~Rectangle();
};

#endif // _SHAPE_H_
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
#include "Shape.h"
#include "DynBase.h"
#include <iostream>
using namespace std;


void Circle::Draw()
{
    cout << "Circle::Draw() ..." << endl;
}
Circle::~Circle()
{
    cout << "~Circle ..." << endl;
}

void Square::Draw()
{
    cout << "Square::Draw() ..." << endl;
}
Square::~Square()
{
    cout << "~Square ..." << endl;
}

void Rectangle::Draw()
{
    cout << "Rectangle::Draw() ..." << endl;
}

Rectangle::~Rectangle()
{
    cout << "~Rectangle ..." << endl;
}

REGISTER_CLASS(Circle);
REGISTER_CLASS(Square);
REGISTER_CLASS(Rectangle);

DynBase.h:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 
#ifndef _DYN_BASE_H_
#define _DYN_BASE_H_

#include <map>
#include <string>
using namespace std;

typedef void *(*CREATE_FUNC)();

class DynObjectFactory
{
public:
    static void *CreateObject(const string &name)
    {
        map<string, CREATE_FUNC>::const_iterator it;
        it = mapCls_.find(name);
        if (it == mapCls_.end())
            return 0;
        else
            return it->second(); //func();

    }

    static void Register(const string &name, CREATE_FUNC func)
    {
        mapCls_[name] = func;
    }
private:
    static map<string, CREATE_FUNC> mapCls_;
};

// g++
// __attribute ((weak))
__declspec(selectany) map<string, CREATE_FUNC> DynObjectFactory::mapCls_;
//頭文件被包含多次,也只定義一次mapCls_;

class Register
{
public:
    Register(const string &name, CREATE_FUNC func)
    {
        DynObjectFactory::Register(name, func);
    }
};

#define REGISTER_CLASS(class_name) \
class class_name##Register { \
public: \
    static void* NewInstance() \
    { \
        return new class_name; \
    } \
private: \
    static Register reg_; \
}; \
Register class_name##Register::reg_(#class_name, class_name##Register::NewInstance)
//CircleRegister

#endif // _DYN_BASE_H_

DynTest.cpp:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
#include "Shape.h"
#include "DynBase.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;



void DrawAllShapes(const vector<Shape *> &v)
{
    vector<Shape *>::const_iterator it;
    for (it = v.begin(); it != v.end(); ++it)
    {
        (*it)->Draw();
    }
}

void DeleteAllShapes(const vector<Shape *> &v)
{
    vector<Shape *>::const_iterator it;
    for (it = v.begin(); it != v.end(); ++it)
    {
        delete(*it);
    }
}


int main(void)
{
    vector<Shape *> v;

    Shape *ps;
    ps = static_cast<Shape *>(DynObjectFactory::CreateObject("Circle"));
    v.push_back(ps);
    ps = static_cast<Shape *>(DynObjectFactory::CreateObject("Square"));
    v.push_back(ps);
    ps = static_cast<Shape *>(DynObjectFactory::CreateObject("Rectangle"));
    v.push_back(ps);

    DrawAllShapes(v);
    DeleteAllShapes(v);


    return 0;
}



在DynBase.h 中#define了一個宏定義REGISTER_CLASS(class_name),且在Shape.cpp 中調用宏定義,拿REGISTER_CLASS(Circle);

來說,程序編譯預處理階段會被替換成:
class CircleRegister { 
public: 

static void* NewInstance() 

return new Circle; 

private: 

static Register reg_; 

}; 
Register CircleRegister::reg_("Circle",CircleRegister::NewInstance);


也即定義了一個新類,且由於含有static 成員,則在main函數執行前先執行初始化,調用Register類構造函數,在構造函數中調用

DynObjectFactory::Register(name, func); 即調用DynObjectFactory 類的靜態成員函數,在Register函數中通過map容器完成了

字符串與函數指針配對的注冊,如mapCls_[name] = func;


進入main函數,調用DynObjectFactory::CreateObject("Circle") ,CreateObject函數中通過string找到對應的函數指針

NewInstance),並且調用后返回創建的對象指針,需要注意的是 return it->second(); 中it->second 是函數指針,后面加括

號表示調用這個函數。對宏定義中的#,##用法不熟悉的可以參考這里

這樣當需要創建多個不同類對象的時候,就不再需要寫很多ifelse的判斷了。


參考:

C++ primer 第四版
Effective C++ 3rd
C++編程規范


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM