这是我参与[第五届青训营]的第九天
SOLID是C++和golang语言共用的设计思想。
S = 单一职责原则
O = 开闭原则
L = Liskov 替换原则
I = 接口隔离原则
D = 依赖倒置/注入
type Command struct {
commandType string args []string
}
type Command struct {
commandType string
args []string
}type CommandFactory struct {
...
}// Create decode and validate the command
func (cf CommandFactory) Create(data []byte) (*Command, error) {
// decode command
command, err := cf.Decode(data)
if err != nil {
return nil, err
}
// validate type
switch cf.Type {
case Foo:
case Bar:
default:
return nil, InvalidCommandType
}
return command, nil
}type CommandExecutor struct {
}// Execute executes the command
func (ce CommandExecutor) Execute(command *Command) ([]byte, error) {
// validate input and execute
switch command.Type {
case Foo:
if len(args) == 0 || len(args[0]) == 0 {
return nil, InvalidInput
}
return ExecuteFoo(command) case Bar: // Bar doesn't take any input
return ExecuteBar(command)
}
}
在面向对象的基于类的语言中,Liskov 替换原则的概念是基类的用户应该能够正确地使用所有派生类。
Liskov 替换原则建议客户端和派生类应通过定义客户端意图的契约进行交互。
在面向对象的基于类的语言中,它指出如果一个类为多个客户端提供方法,那么与其让一个通用接口加载所有方法,不如为每个客户端提供一个单独的接口并在类中实现所有这些方法。
要遵循的规则是每个 接口必须以一种方式定义,以便它提供至少一个客户端所需的准确和完整的功能集。这也意味着如果只有一个客户端使用,则无需破坏接口。
在面向对象的基于类的语言中,它声明模块之间的每个依赖项都应该以抽象类或接口为目标。任何依赖项都不应针对具体类。
开闭原则: 实体应该对扩展开放,对修改关闭。 c++代码如下图:
Product apple{"Apple", Color::Green, Size::Small};
Product tree{"Tree", Color::Green, Size::Large};
Product house{"House", Color::Blue, Size::Large};
ProductList all{apple, tree, house};
BetterFilter bf;
ColorSpecification green(Color::Green);
auto green_things = bf.filter(all, green);
for (auto& product : green_things)
std::cout << product.name << " is green" << std::endl;
SizeSpecification big(Size::Large);
// green_and_big is a product specification
AndSpecification<Product> green_and_big{big, green};
auto green_big_things = bf.filter(all, green_and_big);
for (auto& product : green_big_things)
std::cout << product.name << " is green and big" << std::endl;