- Expert C++
- Vardan Grigoryan Shunguang Wu
- 251字
- 2021-06-24 16:34:04
Design patterns
Design patterns are one of the most expressive tools for programmers. They allow us to solve design problems in an elegant and well-tested way. When you are struggling to provide the best possible design of your classes and their relationship, a well-known design pattern may come to the rescue.
The simplest example of a design pattern is a Singleton. It provides us with a way to declare and use only one instance of the class. For example, suppose that the e-commerce platform has only one Warehouse. To access the Warehouse class, the project may require that we include and use it in many source files. To keep things in sync, we should make the Warehouse a Singleton:
class Warehouse {
public:
static create_instance() {
if (instance_ == nullptr) {
instance_ = new Warehouse();
}
return instance_;
}
static remove_instance() {
delete instance_;
instance_ = nullptr;
}
private:
Warehouse() = default;
private:
static Warehouse* instance_ = nullptr;
};
We declared a static Warehouse object and two static functions for creating and destroying the corresponding instance. The private constructor leads to a compile error each time the user tries to declare a Warehouse object in the old way. To be able to use the Warehouse, the client code has to call the create_instance() function:
Warehouse* w = Warehouse::create_instance();
Product book;
w->add_product(book);
Warehouse::remove_instance();
The singleton implementation of the Warehouse is not complete and is just an example to introduce design patterns. We will introduce more design patterns throughout this book.
- The Supervised Learning Workshop
- 解構(gòu)產(chǎn)品經(jīng)理:互聯(lián)網(wǎng)產(chǎn)品策劃入門寶典
- Android Jetpack開發(fā):原理解析與應用實戰(zhàn)
- Vue.js快跑:構(gòu)建觸手可及的高性能Web應用
- 程序員數(shù)學:用Python學透線性代數(shù)和微積分
- Spring Boot+Spring Cloud+Vue+Element項目實戰(zhàn):手把手教你開發(fā)權(quán)限管理系統(tǒng)
- C語言程序設(shè)計實踐教程
- 零基礎(chǔ)學單片機C語言程序設(shè)計
- 微前端設(shè)計與實現(xiàn)
- Python硬件編程實戰(zhàn)
- MongoDB Cookbook
- Cinder:Begin Creative Coding
- Improving your Penetration Testing Skills
- 打造流暢的Android App
- Swift從入門到精通 (移動開發(fā)叢書)