enum Classifier { NONE, BREAD, BISCUITS, CROISSANTS };
class Product {
private:
std::string name; // Наименование товара
Classifier category; // Классификатор товара
float weight; // Вес нетто
double price; // Цена
public:
Product() : category(Classifier::NONE), weight(0), price(0) {}
Product(std::string name, Classifier category, float weight, double price) :
name(name), category(category), weight(weight), price(price) {}
Classifier getCategory() const { return category; }
float getWeight() const { return weight; }
double getPrice() const { return price; }
};
class Manufacturer {};
class SpecificProduct : public Product {
private:
Manufacturer manufactured; // Производитель
public:
SpecificProduct(std::string name, Classifier category, float weight, double price, Manufacturer manufactured) :
Product(name, category, weight, price) {
this->manufactured = manufactured;
}
Manufacturer getManufactured() const { return manufactured; }
};
class IComparer {
public:
virtual bool equal(const Product& first, const Product& second) const = 0;
};
class ClearMatch : public IComparer {
public:
virtual bool equal(const Product& first, const Product& second) const {
return first.getCategory() == second.getCategory()
and first.getWeight() == second.getWeight()
and first.getPrice() == second.getPrice();
}
};
class FuzzyMatch : public IComparer {
public:
virtual bool equal(const Product& first, const Product& second) const {
return first.getCategory() == second.getCategory()
and first.getWeight() == second.getWeight()
and (first.getPrice() < 120
or first.getPrice() > 80);
}
};
class Comparison {
private:
std::shared_ptr<Product> product;
std::shared_ptr<IComparer> predicate;
public:
Comparison(const std::shared_ptr<Product> product, std::shared_ptr<IComparer> predicate) {
this->product = product;
this->predicate = predicate;
}
inline bool operator()(const std::shared_ptr<Product>& obj) const {
return predicate->equal(*this->product, *obj);
}
};
int main() {
std::list<std::shared_ptr<Product>> products{
std::make_shared<SpecificProduct>("Хлеб", Classifier::BREAD, 0.9f, 100, Manufacturer()),
std::make_shared<SpecificProduct>("Другой хлеб", Classifier::BREAD, 1.0f, 100, Manufacturer()),
std::make_shared<SpecificProduct>("Печенье", Classifier::BISCUITS, 1.0f, 200, Manufacturer())
};
std::shared_ptr<Product> findWhat = std::make_shared<SpecificProduct>("", Classifier::BREAD, 1.0f, 100, Manufacturer());
Comparison compare(findWhat, std::make_shared<ClearMatch>());
auto result = std::ranges::find_if(products, compare);
if (result != products.end()) {
std::cout << "Test passed!!!" << std::endl;
}
}
Максимально странная попытка описать инверсию зависимостей на примерах каких-то светильников, да еще и в сочетании с моделями, и объектами предметной области... И я знаю, что компилятору пофигу, но есть же в конце-концов какие-то соглашения по стилистики написания кода.