C++ 设计模式 02:面向对象 SOLID 设计原则

Single Responsibility Principle 单一职责原则

  • 每个类只负责一项职责,因此也只有一个变化点
  • 在一个结构体系里,如果经常需要在多个类中同步地做相同的改动,那通常意味着设计不良
  • 杜绝“万能类”
class Journal
{
   
   
public:
  explicit Journal(const string& _title) : title(_title) {
   
   }
  void add(const string& entry);      // OK, this is Journal's responsibility
  void save(const string& filename);  // BAD! This is NOT Journal's responsibility
  
  vectoe<string> entries;

private:
  string title;
};

// 向 Journal 中添加、维护新条目是 Journal 的职责,由 Journal 实现
void Journal::add(const string& entry)
{
   
   
  static int count = 1;
  entries.push_back(boost::lexical_cast<string>(count++) + ": " + entry);
}

// 不良设计:
// 将日记保存至文件(或其他存储设备)不是 Journal 的职责,应由专门的类实现!
// 如果存在一系列与 Journal 相似的类,又存在多种存储方案(如存至云),
// 则必然出现代码“牵一发而动全身”,对存储方案的更改会引起多处代码变动
void Journal::save(const string& filename)
{
   
   
  ofstream ofs(filename);
  for (auto& entry : entries)
    ofs << entry << endl;
}

// 设计专门负责存储的类
class SaveManager
{
   
   
public:
  static void save(const Journal& jrnl, const string& filename)
  {
   
   
    ofstream ofs(filename);
    for (auto& entry : jrnl.enties)
      ofs << entry << endl;
  }
};

Open-Closed Principle 开放封闭原则

  • 对扩展开放,对更改封闭,也就是说,对于已经编译好的模块不允许再更改(然后进入重新编译、测试的循环),但允许添加新的模块,从而只需要编译新模块然后将其链接进系统
enum class Color {
   
   Red, Green, Blue};
enum class Size {
   
   Small, Medium, Large};

// 一个以颜色和尺寸区分的产品
struct Product
{
   
   
  string name;
  Color color;
  Size size;
};

// 产品筛选器
class ProductFilter
{
   
   
public:
  using Items = vector<Product*>;

  // 按颜色筛选
  Items by_color(Items items, Color color)
  {
   
   
    Items result;
    for (const auto& item : items)
      if (item->color == color)
        result.push_back(item);
    return result;
  }
  
  // 按尺寸
  Items by_size(Items items, Size size)
  {
   
   
    Items result;
    for (const auto& item : items)
      if (item->size == size)
        result.push_back(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值