title: "modern C++ DesignPattern-Part2"
date: 2018-04-10T19:08:49+08:00
lastmod: 2018-04-11T19:08:49+08:00
keywords: [设计模式, C++]
tags: [设计模式]
categories: []

Part2设计模式和结构化有较强的联系,分成两个part来解释,这篇主要包括桥接,适配器,装饰器这三种

Bridge

优点:

  • 通过这种模式可以将大量的没用到的成员与方法隐藏起来,只暴露出公用接口,降低复杂性
  • 可以通过前向声明 impl,把大量的include放到 impl.cpp里面,降低编译成本
struct Person{
std::string name;
class PersonImpl;
PersonImpl *impl; // bridge - not necessarily inner class, can vary
Person();
~Person();
void greet();
};
struct Person::PersonImpl
{
void greet(Person* p);
}; void Person::PersonImpl::greet(Person* p){
printf("hello %s", p->name.c_str());
}
Person::Person(): impl(new PersonImpl){}
Person::~Person(){ delete impl;}
void Person::greet(){ impl->greet(this);}

这个例子就是通过PersonImpl把大量的实现细节隐藏到了这个类里面,brpc中的server搭建就有很经典的使用. tips: Plmpl 编译防火墙 解除了接口与实现之间的耦合关系,从而降低文件间的编译依赖关系


Composite

这个模式比较简单,直接看代码,这是神经网络的neuron类例子

template <typename Self>
struct SomeNeurons { //主要是为了封装connect_to
template <typename T> void connect_to(T& other){
for (Neuron& from : *static_cast<Self*>(this)){
for (Neuron& to : other){
from.out.push_back(&to);
to.in.push_back(&from);
}
}
}
}; struct Neuron : SomeNeurons<Neuron>{
vector<Neuron*> in, out;
unsigned int id;
Neuron(){
static int id = 1; //static标记id,很方便
this->id = id++;
}
Neuron* begin() { return this; }
Neuron* end() { return this + 1; }
}; struct NeuronLayer : vector<Neuron>, SomeNeurons<NeuronLayer>{
NeuronLayer(int count){
while (count-- > 0)
emplace_back(Neuron{});
} //继承vector用来组合neuron向量,继承SomeNeurons用来解决连接问题
};

Decorator

C++11给这个模式带了了很多新东西,一起来看看吧

Dynamic Decorator

struct Shape{
virtual string str() const = 0;
};
struct ColoredShape : Shape{ //装饰类
Shape& shape;
string color;
ColoredShape(Shape& shape, const string& color): shape{shape}, color(color){}
string str() const override{...}
};
struct Circle: Shape {
float radius;
CirCle(float radius): radius(radius){}
resize(float factor) {radius *= factor};
string str() const override{...}
} Circle circle(0.6);
ColoredShape redCircle(circle, "red"); //shape引用

Static Decorator

前面动态类型的一个缺点是说被修饰的redCircle无法访问circle的方法, 比如 redCircle.resize(2) 编译不通过,下面这个实现方法就是为了解决这个问题的。这个方法的缺点是再编译期进行的装饰,没法重组合。

template <typename T>
struct ColoredShape: T{
static_assert(is_base_of<Shape,T>::value, "template arg must be a Shape");
string color;
ColoredShape(Shape& shape, string color): shape(shape), color(color){}
string str(){...}
}; ColoredShape<TransparentShape<Square>> square{"blue"}; //可以访问所有被修饰的层以及原本的square的所有成员
square.size = 2;
square.transparency = 0.5;
square.resize(3);

这里还有个缺点,通过这种方法,我们没法调用一次构造函数实现所有成员+修饰成员的初始化,解决方法为可变参数模板+类型推导

template <typename T>
struct TransparentShape: T{
int trans;
template<typename ...Args>
TransparentShape(const int trans, Args ...args):
T(std::forward<Args>(args)...), trans(trans){}
...
} ColoredShape2<TransparentShape2<Square>> sq = { "red", 51, 5 }; //这样初始化就没问题了

Functional Decorator

针对函数的装饰器

//1.不需要返回值
template <typename Func>
struct Logger2{
Func func;
string name;
Logger2(const Func& func, const string& name)
: func{func},
name{name}{}
void operator()() const{
cout << "Entering " << name << endl;
func();
cout << "Exiting " << name << endl;
}
}; template <typename Func>
auto make_logger2(Func func,
const string& name){
return Logger2<Func>{ func, name };
}
//call
auto call = make_logger2([](){cout<<"count"<<endl;}, "HelloFunc");
call();

还有一种是当有入参和返回值的需求时, 可变参数模板

template <typename> struct Logger3;  //为啥这里需要先部分特化的声明?
template <typename R, typename... Args>
struct Logger3<R(Args...)>
{
Logger3(function<R(Args...)> func, const string& name)
: func{func},
name{name}{}
R operator() (Args ...args){
cout << "Entering " << name << endl;
R result = func(args...);
cout << "Exiting " << name << endl;
return result;
} function<R(Args ...)> func;
string name;
}; template <typename R, typename... Args>
auto make_logger3(R (*func)(Args...), const string& name){
return Logger3<R(Args...)>(
std::function<R(Args...)>(func),
name);
} double add(double a, double b){
cout << a << "+" << b << "=" << (a + b) << endl;
return a + b;
} //call
auto logged_add = make_logger3(add, "Add");
auto result = logged_add(2, 3);

DesignPattern-part2的更多相关文章

  1. Linux平台 Oracle 10gR2(10.2.0.5)RAC安装 Part2:clusterware安装和升级

    Linux平台 Oracle 10gR2(10.2.0.5)RAC安装 Part2:clusterware安装和升级 环境:OEL 5.7 + Oracle 10.2.0.5 RAC 3.安装Clus ...

  2. Linux平台 Oracle 11gR2 RAC安装Part2:GI安装

    三.GI(Grid Infrastructure)安装 3.1 解压GI的安装包 3.2 安装配置Xmanager软件 3.3 共享存储LUN的赋权 3.4 使用Xmanager图形化界面安装GI 3 ...

  3. Hadoop入门学习笔记---part2

    在<Hadoop入门学习笔记---part1>中感觉自己虽然总结的比较详细,但是始终感觉有点凌乱.不够系统化,不够简洁.经过自己的推敲和总结,现在在此处概括性的总结一下,认为在准备搭建ha ...

  4. 小课堂week13 Clean Code Part2

    Clean Code Part2 对象与数据结构 首先让我们进行一个严肃的思考,对象与数据结构的区别在哪里? 如下两段代码分别用数据结构和对象的方法来描述了一个Point. public class ...

  5. K2 Blackpearl开发技术要点(Part2)

    转:http://www.cnblogs.com/dannyli/archive/2012/09/14/2685282.html K2 Blackpearl开发技术要点(Part2)  

  6. 小课堂Week9 例外处理设计的逆袭Part2

    小课堂Week9 例外处理设计的逆袭Part2 今天继续阅读<例外处理设计的逆袭>这本书,我们先看两个案例: 案例1 问:如果要设计一个依据学号到数据库中查询学生资料的函数,当找不到符合条 ...

  7. 《数字图像处理原理与实践(MATLAB版)》一书之代码Part2

    本文系<数字图像处理原理与实践(MATLAB版)>一书之代码系列的Part2(P43~80),代码运行结果请參见原书配图,建议下载代码前阅读下文: 关于<数字图像处理原理与实践(MA ...

  8. Linux平台 Oracle 12cR2 RAC安装Part2:GI配置

    Linux平台 Oracle 12cR2 RAC安装Part2:GI配置 三.GI(Grid Infrastructure)安装 3.1 解压GI的安装包 3.2 安装配置Xmanager软件 3.3 ...

  9. 自动化测试 Appium之Python运行环境搭建 Part2

    Appium之Python运行环境搭建 Part2 by:授客 QQ:1033553122 实践环境 参见 Appium之Python运行环境搭建 Part1 环境部署 1.安装Android SDK ...

  10. Linux平台 Oracle 18c RAC安装Part2:GI配置

    三.GI(Grid Infrastructure)安装 3.1 解压GI的安装包 3.2 安装配置Xmanager软件 3.3 共享存储LUN的赋权 3.4 使用Xmanager图形化界面配置GI 3 ...

随机推荐

  1. HTML转为PDF,图片导出失败的终极解决方案

    如题项目有需求将一个页面导出为pdf,然而页面中的图片却始终无法导出成功 文章目录 一.导出的方法 二.初步测试的结果 三.使用f12查找原油 四.方案一 五.方案二 六.方案三 七.完整代码 1.使 ...

  2. INFINI Labs 产品更新 | Console 新增数据比对、新增数据看板表格组件及支持下钻功能等

    INFINI Labs 产品更新啦~,本次产品版本更新包括 Gateway v1.14.0.Console v1.2.0.Easysearch v1.1.1 等,其中 Console 在上一版基础上做 ...

  3. linux 条件语句和逻辑判断

    目录 一.条件判断 二.逻辑判断 三.if和case 四.七个实验 一.条件判断 1.test测试 test [ 条件表达式 ] -e:测试目录是否存在 -d:测试是否为目录    -f:是否为文件 ...

  4. odoo部署安全性问题

    本文档描述在生产中或在面向Internet的服务器上设置Odoo的基本步骤.它是在安装之后进行的,对于没有在internet上公开的开发系统来说,它通常不是必需的.警告如果您正在设置公共服务器,请务必 ...

  5. 使用 Docker 分析高通量测序数据

    端午节假期,先祝各位 Bio IT 的爱好者们,节日快乐! 做生信的童鞋想要学习 Docker,或者使用 Docker+Pipeline 封装自己的一套数据分析流程,相信一定不能错过胡博强老师在201 ...

  6. Python 自动化测试的配置层实现方式对标与落地

    Python中什么是配置文件,配置文件如何使用,有哪些支持的配置文件等内容,话不多说,让我们一起看看吧~ 1 什么是配置文件? 配置文件是用于配置计算机程序的参数和初始化设置的文件,如果没有这些配置程 ...

  7. ARC118E Avoid Permutations

    题意 给定一个长度为 \(n\) 的排列 \(p\),在一个 \((n + 2)\times(n + 2)\) 的网格上,禁止通过 \((i, p_i)\) 这些点,每次只能向上或右走一格,从 \(( ...

  8. 10. Mybatis的缓存

    1. Mybatis 的一级缓存 ‍ 一级缓存是 SqlSession 级别的,通过同一个 SqlSession 查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问 , ...

  9. 解读XML - Foreach循环

    <foreach item="item" index="index" collection="supplyIdAry" open=&q ...

  10. 从Excel 电子表格中读取数据并插入到数据库的简单方式

    using (FileStream fileStreamRead = new FileStream("new.xls" , FileMode.Open )) { //创建工作簿 I ...