在C++中实现多属性匹配设计模式,通常涉及到设计一个灵活的类结构,以便能够根据多个属性进行对象的筛选或匹配。这种模式在很多领域都有应用,例如在数据库查询、图形界面过滤、或者任何需要基于多个条件筛选数据的应用中。

  1. 定义基础属性类
    首先,定义一个基础属性类,该类可以存储单个属性的值和类型信息。
#include <string>
#include <variant>
#include <iostream>
#include <vector>
 
class Attribute {
public:
    enum class Type {
        Int,
        String,
        Double
    };
 
    Attribute(std::string name, std::variant<int, std::string, double> value, Type type)
        : name(name), value(value), type(type) {}
 
    std::string getName() const { return name; }
    std::variant<int, std::string, double> getValue() const { return value; }
    Type getType() const { return type; }
 
private:
    std::string name;
    std::variant<int, std::string, double> value;
    Type type;
};
  1. 定义对象类
    定义一个对象类,该类可以包含多个属性。
class Object {
public:
    void addAttribute(const Attribute& attr) {
        attributes.push_back(attr);
    }
 
    std::vector<Attribute> getAttributes() const { return attributes; }
 
private:
    std::vector<Attribute> attributes;
};
  1. 实现匹配逻辑
    创建一个匹配器类,用于根据给定的属性列表匹配对象。
class Matcher {
public:
    bool match(const Object& obj, const std::vector<Attribute>& criteria) const {
        for (const auto& criterion : criteria) {
            bool matched = false;
            for (const auto& attr : obj.getAttributes()) {
                if (attr.getName() == criterion.getName()) {
                    if (attr.getType() == criterion.getType()) {
                        if (std::visit([&](auto&& arg) { return arg == std::get<decltype(arg)>(criterion.getValue()); }, attr.getValue())) {
                            matched = true;
                            break; // 如果找到了匹配的属性,则不再继续查找当前准则的更多属性。
                        }
                    }
                }
            }
            if (!matched) return false; // 如果任何准则未匹配,则返回false。
        }
        return true; // 所有准则都匹配。
    }
};
  1. 使用示例
int main() {
    Object obj1;
    obj1.addAttribute(Attribute("age", 30, Attribute::Type::Int));
    obj1.addAttribute(Attribute("name", "Alice", Attribute::Type::String));
    obj1.addAttribute(Attribute("salary", 60000.0, Attribute::Type::Double));
    
    std::vector<Attribute> criteria = { 
        Attribute("age", 30, Attribute::Type::Int), 
        Attribute("salary", 60000.0, Attribute::Type::Double) 
    };
    Matcher matcher;
    bool result = matcher.match(obj1, criteria); // 应该返回true,因为所有条件都匹配。
    std::cout << "Match result: " << std::boolalpha << result << std::endl; // 输出Match result: true。
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐