1 Star 0 Fork 0

Fingsinz/DesignPatternsInCpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.cpp 1.30 KB
一键复制 编辑 原始数据 按行查看 历史
Fingsinz 提交于 2024-07-29 17:10 . added 策略模式
#include <iostream>
#include <memory>
class Discount {
public:
virtual ~Discount() = default;
virtual void apply(int price) = 0;
};
class TenPercentDiscount : public Discount {
public:
void apply(int price) override {
std::cout << static_cast<int>(price * 0.9) << std::endl;
}
};
class FullDiscount : public Discount {
public:
void apply(int price) {
if (price >= 300) {
price -= 40;
} else if (price >= 200) {
price -= 25;
} else if (price >= 150) {
price -= 15;
} else if (price >= 100) {
price -= 5;
}
std::cout << price << std::endl;
}
};
class Context {
public:
void setDiscount(Discount *discount) {
m_discount = std::unique_ptr<Discount>(discount);
}
void applyDiscount(int price) {
m_discount->apply(price);
}
private:
std::unique_ptr<Discount> m_discount;
};
int main() {
int n;
std::cin >> n;
while (n--) {
int price, type;
std::cin >> price >> type;
Context context;
if (type == 1) {
context.setDiscount(new TenPercentDiscount());
} else if (type == 2) {
context.setDiscount(new FullDiscount());
}
context.applyDiscount(price);
}
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fingsinz/design-patterns-in-cpp.git
git@gitee.com:fingsinz/design-patterns-in-cpp.git
fingsinz
design-patterns-in-cpp
DesignPatternsInCpp
master

搜索帮助