那可以做网站,模板网站和定制网站有什么区别,asp.net p2p网站开发,小程序注册条件开闭原则要求我们在编写代码时#xff0c;尽量不去修改原先的代码#xff0c;当出现新的业务需求时#xff0c;应该通过增加新代码的形式扩展业务而不是对原代码进行修改。
假如我们现在有一批产品#xff0c;每个产品都具有颜色和大小#xff0c;产品其定义如下#xf…开闭原则要求我们在编写代码时尽量不去修改原先的代码当出现新的业务需求时应该通过增加新代码的形式扩展业务而不是对原代码进行修改。
假如我们现在有一批产品每个产品都具有颜色和大小产品其定义如下
enum class Color { Red, Green, Blue };
enum class Size { Small, Medium, Large };struct Product
{string name;Color color;Size size;
};这里 Product 定义为 struct 是因为 struct 默认的访问权限是公有方便书写并且 struct 除了访问权限其他语法与 class 相同。
我们现在需要给一组产品提供过滤功能。于是定义下面的过滤器
struct ProductFilter
{using Items vectorProduct*;
}当我们需要针对 Color 的过滤时我们增加方法 by_color
struct ProductFilter
{using Items vectorProduct*;// 新增方法 by_colorItems by_color(Items items, Color color);
}当我们需要针对 Size 的过滤时我们增加方法 by_size
struct ProductFilter
{using Items vectorProduct*;Items by_color(Items items, Color color);// 新增方法 by_sizeItems by_size(Items items, Size size);
}当我们需要针对 Color 和 Size 同时满足的筛选时再添加…
可以看出当我们有新的需求时必须要对 ProductFilter 类进行修改并没有遵循开闭原则所以我们希望重新设计使这个程序满足开闭原则重构主要用到 template 模版编程。
首先我们需要将过滤器分为两部分过滤器本身和指定的过滤规范。
首先我们先定义一个规范接口不同的过滤需求将通过继承此接口来满足
template typename T
struct Specification
{virtual bool is_satisfied(T* item) 0;
}这里的类型 T 可以由我们自由地指定我们可以指定为类型 Product 也可以指定为其他类型这就意味着这个规范将不再局限于 Product我们可以在任何其他类型中使用它。
接下来是过滤器接口的定义
template typename T
struct Filter
{virtual vectorT* filter(vectorT* items, SpecificationT spec) const 0;
}同样地这里使用模版编程来让过滤器不局限于对 Product 进行过滤。在虚函数 filter 中我们接受 T 类型的容器并通过 Specification 指定过滤规范。
然后我们需要继承 Filter 实现针对于 Product 的过滤器 cpp
struct BetterFilter: FilterProduct
{vectorProduct* filter(vectorProduct* items, SpecificationProduct spec) const override {vectorProduct* result;for(auto p: items) {if(spec.is_satisfied(p)) {result.push_back(p);}}return result;}
};在 filter 方法中我们会调用 Specification 中实现过滤规范对 vectorProduct* 容器中的对象进行筛选。
当我们有了以上的过滤器和规范接口之后我们便可以在不修改代码的情况下扩展业务了。
比如当我们需要对于颜色的过滤器时我们只需要继承 Specification 并覆盖 is_satisfied 方法来实现颜色的过滤法则即可达到我们的目的
// 颜色筛选规范
struct ColorSpecification : SpecificationProduct
{Color color;explicit ColorSpecification(const Color color) : color(color) {}bool is_satisfied(Product* item) override {return item-color color;}
};当我们需要针对 Size 的过滤时
// 大小筛选规范
struct SizeSpecification : SpecificationProduct
{Size size;explicit SizeSpecification(const Size size) : size(size) {}bool is_satisfied(Product* item) override {return item-size size;}
};可以看到我们不再需要修改过滤器来达到我们的目的很显然我们遵从了开闭原则。
需要查看完整的示例代码可以访问 Github 仓库 GnCDesignPatterns。
参考C20设计模式