目录
策略模式(Strategy Pattern)
策略模式是一种行为型设计模式,它定义了一个系列的算法,并将每一个算法封装起来,使它们可以相互替换。策略模式让算法的变化独立于使用算法的客户。
策略模式主要包含以下角色:
1. Context(上下文):用一个具体策略对象来配置,维护一个对策略对象的引用。
2. Strategy(策略接口):定义所有支持的算法的公共接口。
3. ConcreteStrategy(具体策略):实现具体的算法。
实际应用
电子商务系统的折扣策略
-- 电子商务系统,可以根据不同的策略应用不同的折扣。
#include <iostream>
#include <memory>
#include <vector>
// 策略接口类
class DiscountStrategy {
public:
virtual double applyDiscount(double price) = 0;
virtual ~DiscountStrategy() = default;
};
// 具体策略类:无折扣
class NoDiscount : public DiscountStrategy {
public:
double applyDiscount(double price) override {
return price;
}
};
// 具体策略类:百分比折扣
class PercentageDiscount : public DiscountStrategy {
private:
double percentage;
public:
PercentageDiscount(double percentage) : percentage(percentage) {}
double applyDiscount(double price) override {
return price * (1 - percentage / 100);
}
};
// 具体策略类:固定金额折扣
class FixedDiscount : public DiscountStrategy {
private:
double discount;
public:
FixedDiscount(double discount) : discount(discount) {}
double applyDiscount(double price) override {
return price - discount;
}
};
// 上下文类
class ShoppingCart {
private:
std::unique_ptr<DiscountStrategy> strategy;
std::vector<double> items;
public:
void setStrategy(std::unique_ptr<DiscountStrategy> strategy) {
this->strategy = std::move(strategy);
}
void addItem(double price) {
items.push_back(price);
}
double calculateTotal() {
double total = 0;
for (double price : items) {
total += strategy->applyDiscount(price);
}
return total;
}
};
// 客户端代码
int main() {
ShoppingCart cart;
cart.addItem(100);
cart.addItem(200);
cart.addItem(300);
cart.setStrategy(std::make_unique<NoDiscount>());
std::cout << "Total price with no discount: " << cart.calculateTotal() << std::endl;
cart.setStrategy(std::make_unique<PercentageDiscount>(10));
std::cout << "Total price with 10% discount: " << cart.calculateTotal() << std::endl;
cart.setStrategy(std::make_unique<FixedDiscount>(50));
std::cout << "Total price with $50 discount: " << cart.calculateTotal() << std::endl;
return 0;
}
文本编辑器的格式化策略
-- 文本编辑器,可以根据不同的策略应用不同的文本格式。
#include <iostream>
#include <memory>
#include <string>
// 策略接口类
class TextFormatStrategy {
public:
virtual std::string format(const std::string& text) = 0;
virtual ~TextFormatStrategy() = default;
};
// 具体策略类:大写格式
class UpperCaseFormat : public TextFormatStrategy {
public:
std::string format(const std::string& text) override {
std::string result = text;
for (char& c : result) {
c = std::toupper(c);
}
return result;
}
};
// 具体策略类:小写格式
class LowerCaseFormat : public TextFormatStrategy {
public:
std::string format(const std::string& text) override {
std::string result = text;
for (char& c : result) {
c = std::tolower(c);
}
return result;
}
};
// 具体策略类:首字母大写格式
class CapitalizedFormat : public TextFormatStrategy {
public:
std::string format(const std::string& text) override {
std::string result = text;
if (!result.empty()) {
result[0] = std::toupper(result[0]);
}
return result;
}
};
// 上下文类
class TextEditor {
private:
std::unique_ptr<TextFormatStrategy> strategy;
public:
void setStrategy(std::unique_ptr<TextFormatStrategy> strategy) {
this->strategy = std::move(strategy);
}
std::string formatText(const std::string& text) {
return strategy->format(text);
}
};
// 客户端代码
int main() {
TextEditor editor;
std::string text = "Hello World!";
editor.setStrategy(std::make_unique<UpperCaseFormat>());
std::cout << "UpperCase: " << editor.formatText(text) << std::endl;
editor.setStrategy(std::make_unique<LowerCaseFormat>());
std::cout << "LowerCase: " << editor.formatText(text) << std::endl;
editor.setStrategy(std::make_unique<CapitalizedFormat>());
std::cout << "Capitalized: " << editor.formatText(text) << std::endl;
return 0;
}
文件压缩策略
-- 文件压缩系统,可以根据不同的策略应用不同的压缩算法。
#include <iostream>
#include <memory>
#include <string>
// 策略接口类
class CompressionStrategy {
public:
virtual void compress(const std::string& file) = 0;
virtual ~CompressionStrategy() = default;
};
// 具体策略类:ZIP压缩
class ZipCompression : public CompressionStrategy {
public:
void compress(const std::string& file) override {
std::cout << "Compressing " << file << " using ZIP compression." << std::endl;
}
};
// 具体策略类:RAR压缩
class RarCompression : public CompressionStrategy {
public:
void compress(const std::string& file) override {
std::cout << "Compressing " << file << " using RAR compression." << std::endl;
}
};
// 具体策略类:7Z压缩
class SevenZipCompression : public CompressionStrategy {
public:
void compress(const std::string& file) override {
std::cout << "Compressing " << file << " using 7Z compression." << std::endl;
}
};
// 上下文类
class FileCompressor {
private:
std::unique_ptr<CompressionStrategy> strategy;
public:
void setStrategy(std::unique_ptr<CompressionStrategy> strategy) {
this->strategy = std::move(strategy);
}
void compressFile(const std::string& file) {
strategy->compress(file);
}
};
// 客户端代码
int main() {
FileCompressor compressor;
std::string file = "example.txt";
compressor.setStrategy(std::make_unique<ZipCompression>());
compressor.compressFile(file);
compressor.setStrategy(std::make_unique<RarCompression>());
compressor.compressFile(file);
compressor.setStrategy(std::make_unique<SevenZipCompression>());
compressor.compressFile(file);
return 0;
}
总结
策略模式通过将算法封装在独立的类中,使得算法的变化独立于使用算法的客户,从而可以提高代码的可扩展性和维护性。