pImpl

文章目录
  1. 1. 示例
  • 参考资料
  • pImpl(Private Implementation 或 Pointer to Implementation)是通过一个私有的成员指针,将指针所指向的类的内部实现数据进行隐藏。

    优点:

    1. 降低模块的耦合。因为隐藏了类的实现,被隐藏的类相当于原类不可见,对隐藏的类进行修改,不需要重新编译原类。
    2. 降低编译依赖,提高编译速度。
    3. 接口与实现分离,提高接口的稳定性。

    示例

    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
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    #ifndef __LINE_H__
    #define __LINE_H__


    //设计模式: PIMPL
    //1. 实现信息隐藏
    //2. 减小编译依赖, 可以用最小的代价平滑的升级库文件,
    //3. 接口与实现进行解耦

    class Line
    {
    public:
    Line(int,int,int,int);
    ~Line();
    void printLine() const;
    private:
    class LineImpl;
    private:
    LineImpl * _pimpl;
    };


    class Line::LineImpl
    {
    class Point
    {
    public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
    cout << "Point(int=0, int=0)" << endl;
    }

    void print() const
    {
    cout << "(" << _ix
    << "," << _iy
    << ")";
    }

    private:
    int _ix;
    int _iy;
    };
    public:
    LineImpl(int x1, int y1, int x2, int y2)
    : _p1(x1, y1)
    , _p2(x2, y2)
    {
    cout << "LineImpl(int,int,int,int)" << endl;
    }

    ~LineImpl() { cout << "~LineImpl()" << endl; }

    void printLine() const;
    private:
    Point _p1;
    Point _p2;
    };

    void Line::LineImpl::printLine() const
    {
    _p1.print();
    cout << " --> ";
    _p2.print();
    cout << endl;
    }

    Line::Line(int x1, int y1, int x2, int y2)
    : _pimpl(new LineImpl(x1, y1, x2, y2))
    {
    cout << "Line(int,int,int,int)" << endl;
    }

    Line::~Line()
    {
    delete _pimpl;
    cout << "~Line()" << endl;
    }

    void Line::printLine() const
    {
    _pimpl->printLine();
    }
    #endif

    参考资料