1 单例模式
题目链接为:小明的购物车
C++代码如下,
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class ShoppingCart {
public:
static ShoppingCart& get_instance() {
static ShoppingCart instance = ShoppingCart(); //静态变量,类的所有对象共用一个
return instance;
}
vector<string>& get_goods() {
return goods;
}
vector<int>& get_cnt() {
return cnt;
}
void show() {
int n = goods.size();
for (int i = 0; i < n; ++i) {
cout << goods[i] << " " << cnt[i] << endl;
}
return;
}
private:
ShoppingCart () {
} //构造函数私有化,防止外部直接实例化类的对象
vector<string> goods;
vector<int> cnt;
};
int main() {
ShoppingCart& shopping_cart = ShoppingCart::get_instance();
string a;
int b;
while (cin >> a >> b) {
shopping_cart.get_goods().emplace_back(a);
shopping_cart.get_cnt().emplace_back(b);
}
shopping_cart.show();
return 0;
}
注意要点:
- 构造函数私有化,防止外部直接实例化
ShoppingCart
类的对象。 - 静态变量
instance
,只会被创建一次,故ShoppingCart
类的所有对象共用一个instance
。又因为变量instance
的类型为ShoppingCart
,故该类只会存在一个实例化对象。
2 工厂方法模式
题目链接:积木工厂
C++代码如下,
#include <iostream>
#include <vector>
using namespace std;
class Block {
public:
virtual void produce() = 0;
};
class CircleBlock : public Block {
void produce() override {
cout << "Circle Block" << endl;
}
};
class SquareBlock : public Block {
public:
void produce() override {
cout << "Square Block" << endl;
}
};
class BlockFactory {
public:
virtual Block* createBlock() = 0;
};
class CircleBlockFactory : public BlockFactory {
public:
Block* createBlock() override {
return new CircleBlock();
}
};
class SquareBlockFactory : public BlockFactory {
public:
Block* createBlock() override {
return new SquareBlock();
}
};
class BlockFactorySystem {
private:
vector<Block*> blocks;
public:
void produceBlocks(BlockFactory* factory, int quantity) {
for (int i = 0; i < quantity; ++i) {
Block* block = factory->createBlock();
blocks.emplace_back(block);
block->produce();
}
}
const vector<Block*>& getBlocks() const {
return blocks;
}
~BlockFactorySystem() {
for (Block* block : blocks) {
delete block;
}
}
};
int main() {
BlockFactorySystem factorySystem;
int productionCount;
cin >> productionCount;
for (int i = 0; i < productionCount; ++i) {
string blockType;
int quantity;
cin >> blockType >> quantity;
if (blockType == "Circle") {
factorySystem.produceBlocks(new CircleBlockFactory(), quantity);
} else if (blockType == "Square") {
factorySystem.produceBlocks(new SquareBlockFactory(), quantity);
}
}
return 0;
}
3 抽象工厂模式
题目链接:家具工厂
C++代码如下,
#include <iostream>
#include <string>
using namespace std;
class Chair {
public:
virtual void showInfo() = 0;
};
class ModernChair : public Chair {
public:
void showInfo() override {
cout << "modern chair" << endl;
}
};
class ClassicalChair : public Chair {
public:
void showInfo() override {
cout << "classical chair" << endl;
}
};
class Sofa {
public:
virtual void displayInfo() = 0;
};
class ModernSofa : public Sofa {
public:
void displayInfo() override {
cout << "modern sofa" << endl;
}
};
class ClassicalSofa : public Sofa {
public:
void displayInfo() override {
cout <<"classical sofa" << endl;
}
};
class FurnitureFactory {
public:
virtual Chair* createChair() = 0;
virtual Sofa* createSofa() = 0;
};
class ModernFurnitureFactory : public FurnitureFactory {
public:
Chair* createChair() override {
return new ModernChair();
}
Sofa* createSofa() override {
return new ModernSofa();
}
};
class ClassicalFurnitureFactory : public FurnitureFactory {
public:
Chair* createChair() override {
return new ClassicalChair();
}
Sofa* createSofa() override {
return new ClassicalSofa();
}
};
int main() {
int N;
cin >> N;
for (int i = 0; i < N; ++i) {
string furnitureType;
cin >> furnitureType;
FurnitureFactory* factory = nullptr;
if (furnitureType == "modern") {
factory = new ModernFurnitureFactory();
} else if (furnitureType == "classical") {
factory = new ClassicalFurnitureFactory();
}
Chair* chair = factory->createChair();
Sofa* sofa = factory->createSofa();
chair->showInfo();
sofa->displayInfo();
delete chair;
delete sofa;
delete factory;
}
return 0;
}
4 建造者模式
题目链接为:自行车加工
C++代码如下,
#include <iostream>
#include <string>
using namespace std;
class Bike {
public:
string frame;
string tires;
void setFrame(const string& frame) {
this->frame = frame;
}
void setTires(const string& tires) {
this->tires = tires;
}
friend ostream& operator<<(ostream& os, const Bike& bike) {
os << bike.frame << " " << bike.tires;
return os;
}
};
class BikeBuilder {
public:
virtual void buildFrame() = 0;
virtual void buildTires() = 0;
virtual Bike getResult() = 0;
};
class MountainBikeBuilder : public BikeBuilder {
private:
Bike bike;
public:
void buildFrame() override {
bike.setFrame("Aluminum Frame");
}
void buildTires() override {
bike.setTires("Knobby Tires");
}
Bike getResult() override {
return bike;
}
};
class RoadBikeBuilder : public BikeBuilder {
private:
Bike bike;
public:
void buildFrame() override {
bike.setFrame("Carbon Frame");
}
void buildTires() override {
bike.setTires("Slim Tires");
}
Bike getResult() override {
return bike;
}
};
class BikeDirector {
public:
Bike construct(BikeBuilder& builder) {
builder.buildFrame();
builder.buildTires();
return builder.getResult();
}
};
int main() {
int N;
cin >> N;
BikeDirector director;
for (int i = 0; i < N; ++i) {
string bikeType;
cin >> bikeType;
BikeBuilder* builder;
if (bikeType == "mountain") {
builder = new MountainBikeBuilder();
} else {
builder = new RoadBikeBuilder();
}
Bike bike = director.construct(*builder);
cout << bike << endl;
delete builder;
}
return 0;
}
5 原型模式
题目链接为:矩阵原型
C++代码如下,
#include <iostream>
#include <string>
#include <vector>
class Prototype {
public:
virtual Prototype* clone() const = 0;
virtual std::string getDetails() const = 0;
virtual ~Prototype() {
}
};
class RectanglePrototype : public Prototype {
private:
std::string color;
int width;
int height;
public:
RectanglePrototype(std::string color, int width, int height) : color(color), width(width), height(height) {
}
Prototype* clone() const override {
return new RectanglePrototype(*this);
}
std::string getDetails() const override {
return "Color: " + color + ", Width: " + std::to_string(width) + ", Height: " + std::to_string(height);
}
};
int main() {
std::vector<Prototype*> rectangles;
int N;
std::cin >> N;
for (int i = 0; i < N; ++i) {
std::string color;
int width, height;
std::cin >> color >> width >> height;
Prototype* originalRectangle = new RectanglePrototype(color, width, height);
rectangles.emplace_back(originalRectangle);
}
for (const auto& rectangle : rectangles) {
Prototype* clonedRectangle = rectangle->clone();
std::cout << clonedRectangle->getDetails() << std::endl;
delete clonedRectangle;
}
for (const auto& rectangle : rectangles) {
delete rectangle;
}
return 0;
}
6 适配器模式
题目链接为:扩展坞
C++代码如下,
#include <iostream>
class USB {
public:
virtual void charge() = 0;
};
class TypeC {
public:
virtual void chargeWithTypeC() = 0;
};
class TypeCAdapter : public USB {
private:
TypeC* typeC;
public:
TypeCAdapter(TypeC* typeC) : typeC(typeC) {
}
void charge() override {
typeC->chargeWithTypeC();
}
};
class NewComputer : public TypeC {
public:
void chargeWithTypeC() override {
std::cout << "TypeC" << std::endl;
}
};
class AdapterCharger : public USB {
public:
void charge() override {
std::cout << "USB Adapter" << std::endl;
}
};
int main() {
int N;
std::cin >> N;
//std::cin.ignore();
for (int i = 0; i < N; ++i) {
int choice;
std::cin >> choice;
if (choice == 1) {
TypeC* newComputer = new NewComputer();
newComputer->chargeWithTypeC();
delete newComputer;
} else if (choice == 2) {
USB* usbAdapter = new AdapterCharger();
usbAdapter->charge();
delete usbAdapter;
}
}
return 0;
}
7 代理模式
题目链接为:小明买房子
C++代码如下,
#include <iostream>
//抽象主题
class HomePurchase {
public:
virtual void requestPurchase(int area) = 0;
};
//真实主题
class HomeBuyer : public HomePurchase {
public:
void requestPurchase(int area) override {
std::cout << "YES" << std::endl;
}
};
//代理类
class HomeAgentProxy : public HomePurchase {
private:
HomeBuyer homeBuyer;
public:
void requestPurchase(int area) override {
if (area > 100) {
homeBuyer.requestPurchase(area);
} else {
std::cout << "NO" << std::endl;
}
}
};
int main() {
HomePurchase* buyerProxy = new HomeAgentProxy();
int n;
std::cin >> n;
for (int i = 0; i < n; ++i) {
int area;
std::cin >> area;
buyerProxy->requestPurchase(area);
}
delete buyerProxy;
return 0;
}
8 装饰模式
题目链接为:咖啡加糖
C++代码如下,
#include <iostream>
#include <memory>
//咖啡接口
class Coffee {
public:
virtual ~Coffee() {
}
virtual void brew() = 0;
};
//具体的黑咖啡类
class BlackCoffee : public Coffee {
public:
void brew() override {
std::cout << "Brewing Black Coffee" << std::endl;
}
};
//具体的拿铁类
class Latte : public Coffee {
public:
void brew() override {
std::cout << "Brewing Latte" << std::endl;
}
};
//装饰者抽象类
class Decorator : public Coffee {
protected:
std::unique_ptr<Coffee> coffee;
public:
Decorator(std::unique_ptr<Coffee> coffee) : coffee(std::move(coffee)) {
}
void brew() override {
if (coffee) {
coffee->brew();
}
}
};
//具体的牛奶装饰者类
class MilkDecorator : public Decorator {
public:
MilkDecorator(std::unique_ptr<Coffee> coffee) : Decorator(std::move(coffee)) {
}
void brew() override {
Decorator::brew();
std::cout << "Adding Milk" << std::endl;
}
};
//具体的糖类修饰者类
class SugarDecorator : public Decorator {
public:
SugarDecorator(std::unique_ptr<Coffee> coffee) : Decorator(std::move(coffee)) {
}
void brew() override {
Decorator::brew();
std::cout << "Adding Sugar" << std::endl;
}
};
//客户端代码
int main() {
int coffeeType, condimentType;
while (std::cin >> coffeeType >> condimentType) {
//根据输入制作咖啡
std::unique_ptr<Coffee> coffee;
if (coffeeType == 1) {
coffee = std::make_unique<BlackCoffee>();
} else if (coffeeType == 2) {
coffee = std::make_unique<Latte>();
} else {
std::cout << "Invalid coffee type" << std::endl;
continue;
}
//根据输入添加调料
if (condimentType == 1) {
coffee = std::make_unique<MilkDecorator>(std::move(coffee));
} else if (condimentType == 2) {
coffee = std::make_unique<SugarDecorator>(std::move(coffee));
} else {
std::cout << "Invalid condiment type" << std::endl;
continue;
}
//输出制作过程
coffee->brew();
}
return 0;
}