官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 马尔康县| 阳谷县| 浙江省| 逊克县| 凌云县| 自贡市| 赤壁市| 平远县| 揭阳市| 大关县| 姚安县| 罗江县| 达州市| 博乐市| 赤城县| 北安市| 阿瓦提县| 库尔勒市| 昌宁县| 澄迈县| 海阳市| 格尔木市| 洪雅县| 姜堰市| 和政县| 望谟县| 清流县| 墨竹工卡县| 台中市| 南川市| 吕梁市| 宁南县| 太保市| 安远县| 碌曲县| 东乌珠穆沁旗| 佳木斯市| 德格县| 丹凤县| 周口市| 龙州县|