首页 > 其他分享 >DesignPattern-part1

DesignPattern-part1

时间:2023-03-24 19:34:30浏览次数:38  
标签:return Database make DesignPattern part1 static unique boost

title: "modern C++ DesignPattern-Part1"
date: 2018-04-03T16:06:33+08:00
lastmod: 2018-04-03T16:06:33+08:00
draft: false
keywords: [设计模式]
tags: [设计模式, C++]
categories: []

现代c++改变了很多设计模式的实现方式,为了保持与时俱进,阅读了"Design Pattern in Modern C++"这本书,会记录下来在阅读中的一些心得体会,Part1主要包括 工厂模式,建造者模式与单例模式的现代实现


Factory

Abstract Factory

struct HotDrinkFactory {
  virtual unique_ptr<HotDrink> make() const = 0;  };
};
struct CoffeeFactory : HotDrinkFactory{
 unique_ptr<HotDrink> make() const override {
 return make_unique<Coffee>();
}};

class DrinkFactory {
  map<string, unique_str<HotDrinkFactory>> hot_factories;
public:
  DrinkFactory(){
   hot_factories["coffee"] = make_unique<CoffeeFactory>();
   hot_factories["tea"] = make_unique<TeaFactory>();
  }
  unique_ptr<HotDrink> make_drink(const string& name) {
   auto drink = hot_factories[name]->make();
   drink->prepare(200); // oops!
   return drink;
  }
};

这种写法避免了简单工厂模式冗长的switch case,会初始化所有的工厂,通过map来调用特殊类的工厂。

Functional Factory

class DrinkWithVolumeFactory
{
 map<string, function<unique_ptr<HotDrink>()>> factories;
public:
DrinkWithVolumeFactory() {
  factories["tea"] = [] {
  	auto tea = make_unique<Tea>(); tea->prepare(200);
  	return tea;
  };
}
inline unique_ptr<HotDrink> DrinkWithVolumeFactory::make_drink(const string& name) {
	return factories[name](); 
 }
};

这种工厂使用了lambda+function,存储了每个name对应的构建方法。不用再继承很多的派生工厂,看起来非常优雅。

tips:

boost::archive::text_oarchive 可以通过stringstream的方式序列化一个类,很方便


Singleton

Old style(double check lock)

class Database {
	// same members as before, but then...
	static Database& instance(); 
private:
	static boost::atomic<Database*> instance; 
	static boost::mutex mtx;
};
Database& Database::instance() {
	Database* db = instance.load(boost::memory_order_consume);
	if (!db) {
		boost::mutex::scoped_lock lock(mtx);
    db = instance.load(boost::memory_order_consume);
		if (!db) {
			db = new Database();
      instance.store(db, boost::memory_order_release);
 		}
  }
}

C++11

class Database{
protected:
  Database();
public:
  static Database& get() {
    static Database database;
    return database;
  }
  //如果不从静态区分配内存,而是从堆上分配
  static Database& get() {
    static Database* database = new Database();
    return *database;
  }
  Database(Database const&) = delete;
  Database(Database&&) = delete;
  Database& operator=(Database const&) = delete;
  Database& operator=(Database &&) = delete;
}

Builder

这个模式实际使用起来比较常见,有个使用方式比较有趣,这里列出来

class PersonAddressBuilder : public PersonBuilderBase {
	typedef PersonAddressBuilder self; 
public:
	explicit PersonAddressBuilder(Person& person) : PersonBuilderBase{ person } {}
	self& at(std::string street_address){
  	person.street_address = street_address;
	 	return *this;
	}

  self& with_postcode(std::string post_code) { ... }
  self& in(std::string city) { ... }
};

//使用,赋值属性后返回引用可以持续进行属性赋值
Person p = Person::create()
  .lives().at("123 London Road")
          .with_postcode("SW1 1GB")
          .in("London")
  .works().at("PragmaSoft")
          .as_a("Consultant")
          .earning(10e6);

标签:return,Database,make,DesignPattern,part1,static,unique,boost
From: https://www.cnblogs.com/sunstrikes/p/17253106.html

相关文章

  • DesignPattern-part3
    title:"modernC++DesignPattern-Part3"date:2018-04-12T19:08:49+08:00lastmod:2018-04-12T19:08:49+08:00keywords:[设计模式,C++]tags:[设计模式]categorie......
  • DesignPattern-part2
    title:"modernC++DesignPattern-Part2"date:2018-04-10T19:08:49+08:00lastmod:2018-04-11T19:08:49+08:00keywords:[设计模式,C++]tags:[设计模式]categorie......
  • Nginx基础02:配置文件nginx.conf(Part1)
    我们使用Nginx主要是通过其配置文件nginx.conf来实现的。按照一定的规则,编写特定的指令,可以帮助我们实现对Web服务的控制!所以,学习Nginx的用法,几乎就是学习nginx.conf!如何......
  • DesignPatternPrinciple-设计模式原则
    1.单一职责原则(SingleResponsibilityPrinciple)类T负责两个不同的职责:职责P1,职责P2。usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSys......
  • rtk 快速实践 part1 创建一个Post
    开发环境搭建(Typescript+RTK模板的使用)嗨,大家好,经过rtk快速上手,下面我们开始真正动手实践吖。cra创建项目提供了Typescript配合redux的模板,这个模板就是下面两行安......
  • 第十八章 用于大型程序的工具 Part1 C++异常处理
    异常基本概念BjarneStroustrup说:提供异常的基本目的就是为了处理上面的问题。基本思想是:让一个函数在发现了自己无法处理的错误时抛出(throw)一个异常,然后它的(直接或者间接......
  • [Unity URP]原神 Shader渲染还原 Part1 面部阴影
    声明本文章的代码仅作为学习交流使用//面部阴影half3faceShadow;#ifFACESHADOW_ONfloat3Front=mul(unity_O......
  • 第七章 类_Part1
    1.类和对象1.1类和对象的基本概念1.1.1C和C++中struct区别c语言struct只有变量c++语言struct既有变量,也有函数1.1.2类的封装​ 我们编写程序的目的是为了解决现......
  • 1.大并发服务器架构Part1
    要提升服务器性能,就要有服务器高性能编程技术,就需要自己编码实现。另外服务器性能的几个性能杀手:1数据拷贝,数据从内核态copy到用户态,或者在用户态之间co......
  • 分布式系统 Lab 2: Primary-Backup Service -Part1
    Lab2:Primary-BackupService-Part1概述此次lab会通过主备份的方式创建容错服务,通过视图服务器(ViewServer)的方式来确定主从服务器,视图服务器监听主从服务器(Primary,Ba......