设计模式之pimpl惯用法C++版
来源:互联网 发布:网络扣字大手排行榜 编辑:程序博客网 时间:2024/05/17 23:34
类D使用类A,类B作为成员变量,
以下是头文件
pattern.h
#ifndef PATTERN_H#define PATTERN_Hclass A{public:A(int m);A();void print();private:int m_a;};class B{public:B(int m);B();void print();private:int m_b;};class D{public:D(int a,int b);void print();private:A m_classA;B m_classB;};#endif
pattern.cpp
#include <iostream>#include "pattern.h"A::A(int m){m_a = m;}A::A(){m_a = 0;}void A::print(){std::cout<<"A "<<m_a<<std::endl;}B::B(int m){m_b = m;}B::B(){m_b =0 ;}void B::print(){std::cout<<"B "<<m_b<<std::endl;}D::D(int a,int b):m_classA(a),m_classB(b){}void D::print(){m_classA.print();m_classB.print();}int main(){D classD(1,2);classD.print();}
A、B与D强耦合。非常不利于后期维护
#ifndef PATTERN2_H#define PATTERN2_Hclass Impl;class D{public:D(int a,int b);void print();~D();private:Impl *m_Impl;};#endif
引入impl指针
pattern2.h
pattern2.cpp
#include <iostream>#include "pattern2.h"class A{public:A(int m);A();void set(int m);void print();private:int m_a;};class B{public:B(int m);B();void set(int m);void print();private:int m_b;};A::A(int m){m_a = m;}A::A(){m_a = 0;}void A::set(int m){ m_a = m;}void A::print(){std::cout<<"A "<<m_a<<std::endl;}B::B(int m){m_b = m;}B::B(){m_b =0 ;}void B::set(int m){ m_b = m;}class Impl{public:A m_classA;B m_classB;};void B::print(){std::cout<<"B "<<m_b<<std::endl;}D::D(int a,int b):m_Impl(new Impl()){m_Impl->m_classA.set(a);m_Impl->m_classB.set(b);}D::~D(){if(m_Impl){delete m_Impl;m_Impl = NULL;}}void D::print(){m_Impl->m_classA.print();m_Impl->m_classB.print();}int main(){D classD(2,1);classD.print();}
通过Impl *m_Impl;大大降低了A、B与D类的耦合,并且A类和B类的内部的修改不会导致包含D类头文件的其他模块重新编译。
阅读全文
0 0
- 设计模式之pimpl惯用法C++版
- 设计模式之pimpl惯用法C语言版(城门失火 殃及池鱼)
- Bridge模式/ Pimpl惯用法 实例
- 设计模式之PIMPL
- pimpl 惯用法的背后
- 重构 — 改善既有的类图设计 条款9:用Pimpl惯用法隐藏细节
- 编译防火墙——C++的Pimpl惯用法解析
- 编译防火墙——C++的Pimpl惯用法解析
- Exceptional C++读书笔记:编译器防火墙与Pimpl惯用法(一)
- Python的惯用法技巧和创建型设计模式
- C/C++惯用法
- C++实现设计模式: PIMPL IDIOM
- PIMPL设计模式的理解和使用
- 柴郡猫技术--C++中的PIMPL设计模式
- 条款31提及pimpl设计模式
- PIMPL设计模式的理解和使用
- PIMPL模式
- PIMPL模式
- python子类调用父类的方法
- 【MyEclipse】myeclipse和mysql的字符编码都设置为utf-8,插入中文依然显示问号
- Android面试——事件的传递机制
- Linux:信号量
- 浅谈Java中static的使用
- 设计模式之pimpl惯用法C++版
- Educational Codeforces Round 24 D. Multicolored Cars 补题
- 内存泄漏检测和静态代码分析等工具简单列举
- Java中的HashCode跟equals重写标准类型
- c语言泛式编程简单入门。
- SUN SPARC T4-4电源故障引起的宕机
- Android数据统计柱状图、折线图 MPAndroidChart
- List集合中的对象根据属性排序
- Android技术之使用Handler引发的内存泄露