2021年01月14日 阅读数：7

Problems

• 至少存在一个数字
• 至少存在一个特殊字符
• 至少同时存在一个大写和小写字母
• ...

• 优势

• 缺点

实现

校验器Validator

• 首先定义基类
``````struct Validator {
virtual ~Validator() {}
virtual bool validate(std::string_view) = 0;
};``````

• 再定义子类
``````struct LengthValidator final : Validator {
LengthValidator(unsigned int length) : length_{length} {}

}

private:
unsigned int length_;
};``````

• 装饰器类
``````struct ValidatorDecorator : Validator {
explicit ValidatorDecorator(std::unique_ptr<Validator> validator) :
impl_(std::move(validator)) {}

virtual bool validate(std::string_view password) override {
}

private:
std::unique_ptr<Validator> impl_;
};``````
• 具体的装饰器类

``````struct DigitalPasswordValidator final : ValidatorDecorator {
ValidatorDecorator(std::move(validator)) {}

}
};``````

``````struct CasePasswordValidator final : ValidatorDecorator {
ValidatorDecorator(std::move(validator)) {}

bool has_lower = false;
bool has_upper = false;

if (islower(ch)) has_lower = true;
else if (isupper(ch)) has_upper = true;
});

return has_lower && has_upper;
}
};``````

``````struct SymbolPasswordValidator final : ValidatorDecorator {
ValidatorDecorator(std::move(validator)) {}

}
};``````

实例

``````int main() {
auto validator = std::make_unique<LengthValidator>(8);

assert(num_validator->validate("abcd123,./"));
assert(!num_validator->validate("abcdvdfs,./"));