当前位置:网站首页>Software Architect - Creative Pattern - singleton pattern - prototype pattern - Factory Method Pattern - Abstract Factory Pattern - builder pattern
Software Architect - Creative Pattern - singleton pattern - prototype pattern - Factory Method Pattern - Abstract Factory Pattern - builder pattern
2022-04-22 14:22:00 【Plug in development】
List of articles
In the practice of object-oriented programming , Facing a large number of object-oriented creation , Classify such creation methods as creation patterns , The main focus of creative design patterns is “ How to create an object ”, Its main feature is “ Separate the creation and use of objects ”. This can reduce the coupling of the system , Users don't need to pay attention to the details of object creation , Object creation is done by the relevant factory . Just like when we go shopping in the mall , You don't need to know how goods are produced , Because they are produced by professional manufacturers .
1. The singleton pattern
Single case (Singleton) Definition of pattern : A class has only one instance , This class can create a pattern of this instance by itself . for example ,Windows Only one task manager can be opened in , This can avoid the waste of memory resources caused by opening multiple task manager windows , Or errors such as inconsistent contents displayed in various windows . In computer system , also Windows The recycle bin 、 File system in operating system 、 Thread pool in multithreading 、 Graphics card driver object 、 Background processing services for printers 、 Connection pool for database 、 Counters for websites 、Web Applied configuration objects 、 Dialog boxes in the application 、 The cache in the system is often designed as a single example .
#include <iostream>
class Singleton {
private:
Singleton(){
std::cout<<"Create Singleton\n";
}
static Singleton* s;
public:
static Singleton* getInstance(){
return s;
}
};
Singleton* Singleton::s=new Singleton();//global init
2. Archetypal model
Prototype (Prototype) The definition of a pattern is as follows : Use an instance that has been created as a prototype , Create a new object that is the same or similar to the prototype by copying the prototype object . ad locum , The prototype instance specifies the kind of object to create . Creating objects in this way is very efficient , There is no need to specify the details of object creation at all . for example ,Windows The installation of the operating system is usually time-consuming , If you copy it a lot faster . When the cost of creating objects directly is high , Then use this mode . for example , An object needs to be created after a costly database operation . We can cache the object , Return its clone on the next request , Update the database when needed , To reduce database calls .
#include <cstdlib>
class Prototype {
public:
int *ip=(int*)malloc(sizeof(int));
int counter=100;
virtual Prototype* clone()=0;
};
class cloneablePrototype:public Prototype{
public:
cloneablePrototype();
Prototype* clone();
private:
cloneablePrototype(const cloneablePrototype&);//copy
cloneablePrototype& operator=(cloneablePrototype const& cloneablePrototype1 );//ban on =operator
};
cloneablePrototype::cloneablePrototype() {
}
Prototype *cloneablePrototype::clone() {
return new cloneablePrototype(*this);
}
cloneablePrototype:: cloneablePrototype(const cloneablePrototype& c){
//pass your stack value and heap value here
counter=c.counter;
*(ip)=*(c.ip);
}//copy
3. Factory method (Factory Method) Pattern
Definition of factory method pattern : Define a factory interface for creating product objects , Postpone the actual creation of the product object to the specific factory class . When the requirements in the creation mode are met “ Create separate from use ” Characteristics . characteristic : Use factories to control the instantiation of subclasses , application : When we explicitly plan to create different instances under different conditions .
#include<iostream>
class Product{
public:
virtual void getType(){
std::cout<<"base type\n";};
};
class ProductA:public Product {
public:
void getType();
};
class ProductB:public Product {
public:
void getType();
};
class ProductC:public Product {
public:
void getType();
};
class Factory {
public:
Product* getProduct(char t);
};
Product* Factory::getProduct(char t){
std::cout<<"producing "<<t<<std::endl;
switch (t){
case 'A':
return new ProductA();
case 'B':
return new ProductB();
case 'C':
return new ProductC();
default:
return nullptr;
}
}
void ProductA::getType() {
std::cout<<"my type is A\n";
}
void ProductB::getType() {
std::cout<<"my type is B\n";
}
void ProductC::getType() {
std::cout<<"my type is C\n";
}
4. Abstract factory (AbstractFactory) Pattern
Definition of abstract factory pattern : It is an interface for access classes to create a set of related or interdependent objects , Its access class can obtain the pattern structure of different levels of products of the same family without specifying the specific class of the product . Factory mode belonging to secondary structure , Each type of product is created for the factory model , Then different types of products are attributed to the same factory model for internal use .
# include < iostream >
//product
class laptop
{
public:
virtual void info() = 0;
laptop();
virtual~laptop();
};
class smartphone
{
public:
virtual void info() = 0;
smartphone();
virtual~smartphone();
};
class samsungLaptop: public laptop
{
public:
void info()
{
std::cout << "laptop made by samsung\n";
}
};
class samsungSmartphone: public smartphone
{
public:
void info()
{
std::cout << "smartphone made by samsung\n";
}
};
class appleLaptop: public laptop
{
public:
void info()
{
std::cout << "laptop made by apple\n";
}
};
class appleSmartphone: public smartphone
{
public:
void info()
{
std::cout << "smartphone made by apple\n";
}
};
//factory
class AbstractFactory
{
public:
virtual smartphone *makePhone() = 0;
virtual laptop *makeLaptop() = 0;
virtual~AbstractFactory();
};
class samsungFactory: public AbstractFactory
{
public:
smartphone *makePhone()
{
return new samsungSmartphone();
}
laptop *makeLaptop()
{
return new samsungLaptop();
}
};
class appleFactory: public AbstractFactory
{
public:
smartphone *makePhone()
{
return new appleSmartphone();
}
laptop *makeLaptop()
{
return new appleLaptop();
}
};
aptop::laptop() {
}
laptop::~laptop() {
}
smartphone::smartphone() {
}
smartphone::~smartphone() {
}
AbstractFactory::~AbstractFactory() {
}
5. builder (Builder) Pattern
In the process of software development, it is sometimes necessary to create a complex object , This complex object is usually composed of several sub parts in certain steps . for example , Computers have CPU、 a main board 、 Memory 、 Hard disk 、 The graphics card 、 The case 、 Monitor 、 keyboard 、 Assembled from mouse and other parts , The buyer can't assemble the computer by himself , Instead, tell the computer sales company the configuration requirements of the computer , The computer sales company arranges technicians to assemble computers , Then give it to the buyer who wants to buy the computer . builder Builder The problem to be solved by the model is : When the object we want to create is very complex ( It is usually composed of many other objects ), We need the creation process of complex object and the representation of this object ( Exhibition ) Separate from , The advantage of this is to build complex objects step by step , Because parameters can be introduced in the construction process of each step , Make the display of the final object created through the same steps different .
#pragma once
#include<iostream>
#include<string>
using namespace std;
class House {
public:
virtual void setWall(const string& str) = 0;
virtual void setWindow(const string& str) = 0;
virtual void setDoor(const string& str) = 0;
virtual void setRoom(const string& str) = 0;
virtual void show() = 0;
virtual ~House() {
}
string wall, Window, door, room;
};
class HouseBuild {
public:
virtual House* GetResult() = 0;
virtual void BuildWall() = 0;
virtual void BuildWindow() = 0;
virtual void BuildDoor() = 0;
virtual void BuildRoom() = 0;
virtual ~HouseBuild() {
}
};
class StoneHouse :public House {
public:
void setWall(const string& str) override{
this->wall = str;
}
void setWindow(const string& str) override {
this->Window = str;
}
void setDoor(const string& str) override {
this->door = str;
}
void setRoom(const string& str) override {
this->room = str;
}
void show()override {
cout << "Stone House data:" << "wall=" << wall << ", window="
<< Window << ", door=" << door << ", room=" <<room<< endl;
}
};
class StoneHouseBuild :public HouseBuild {
public:
StoneHouseBuild(StoneHouse* pStoneHouse) {
this->pStoneHouse = pStoneHouse;
}
void BuildWall() override{
cout << "Stone Wall" << endl;
pStoneHouse->setWall("Stonewall");
}
void BuildWindow() override {
cout << "Stone Window" << endl;
pStoneHouse->setWindow("Stonewindow");
}
void BuildDoor() override {
cout << "Stone Door" << endl;
pStoneHouse->setDoor("Stonedoor");
}
void BuildRoom() override {
cout << "Stone Room" << endl;
pStoneHouse->setRoom("Stoneroom");
}
House* GetResult()override {
return pStoneHouse;
}
~StoneHouseBuild() {
delete pStoneHouse;
this->pStoneHouse = nullptr;
}
private:
StoneHouse* pStoneHouse;
};
class WoodHouse :public House {
public:
void setWall(const string& str) override {
this->wall = str;
}
void setWindow(const string& str) override {
this->Window = str;
}
void setDoor(const string& str) override {
this->door = str;
}
void setRoom(const string& str) override {
this->room = str;
}
void show()override {
cout << "Wood House data:" << "wall=" << wall << ", window="
<< Window << ", door=" << door << ", room=" <<room<< endl;
}
};
class WoodHouseBuild :public HouseBuild {
public:
WoodHouseBuild(WoodHouse* pWoodHouse) {
this->pWoodHouse = pWoodHouse;
}
void BuildWall() override {
cout << "Wood Wall" << endl;
pWoodHouse->setWall("Woodwall");
}
void BuildWindow() override {
cout << "Wood Window" << endl;
pWoodHouse->setWindow("Woodwindow");
}
void BuildDoor() override {
cout << "Wood Door" << endl;
pWoodHouse->setDoor("Wooddoor");
}
void BuildRoom() override {
cout << "Wood Room" << endl;
pWoodHouse->setRoom("Woodroom");
}
House* GetResult()override {
return pWoodHouse;
}
~WoodHouseBuild() {
delete pWoodHouse;
this->pWoodHouse = nullptr;
}
private:
WoodHouse* pWoodHouse;
};
ad locum , Take building a house as an example . The order of building houses is the same , All are Wall、Window、Door、Room, This part is fixed , So take this part out as a whole and put it in another abstract base class HouseBuild In the implementation of , Achieve separation . Each type of house inherits from the abstract base class House, The corresponding house building algorithm inherits from the abstract base class HouseBuild.
#include<iostream>
#include"Build.h"
using namespace std;
class HouseDirector {
public:
HouseBuild* pHouseBuild;
HouseDirector(HouseBuild* pHouseBuild){
this->pHouseBuild = pHouseBuild;
}
// The process is the same , The stability of the
House* Construct() {
pHouseBuild->BuildWall();
pHouseBuild->BuildWindow();
pHouseBuild->BuildDoor();
pHouseBuild->BuildRoom();
return pHouseBuild->GetResult();
}
~HouseDirector() {
delete pHouseBuild;
this->pHouseBuild = nullptr;
}
};
int main()
{
HouseBuild* pHouse1 = new StoneHouseBuild(new StoneHouse());
HouseDirector* director1 = new HouseDirector(pHouse1);
director1->Construct()->show();
cout << "===========" << endl;
HouseBuild* pHouse2 = new WoodHouseBuild(new WoodHouse());
HouseDirector* director2 = new HouseDirector(pHouse2);
director2->Construct()->show();
return 0;
}
among Construct The method is stable . In this way, the separation of construction and representation is realized . Object oriented design pattern reflects the consistency of abstract concrete class behavior .
These build patterns , It reflects the general abstract in the base class , Properties and methods of regularity , The specific implementation is deferred to the subclass , The design of base class embodies the most important part of software implementation .
Reasonable script code can effectively improve work efficiency , Reduce repetitive labor .
6. Author Q & A
If you have any questions , Please leave a message .
版权声明
本文为[Plug in development]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221416400988.html
边栏推荐
- Binarytree practice binary tree sequence traversal 𞓜 sequence traversal with queue
- Double pointer fast and slow pointer 𞓜 happy number, search repetition number 202, 287, | 141, 142, 143, 234, 457
- jar 反编译(decode compiler) 在线工具
- Binarytree exercises constructing binary trees from traversal sequences of front order and middle order, middle order and back order | reconstructing binary trees 654, 105 and 106
- 10天完成民猫电商毕设——用户模块实现(2nd day)
- shell入门使用
- Dynamic gauge initial solution 𞓜 maximum subsequence and longest ascending subsequence 53 and 128
- Leetcode (04)
- TopK
- Shiro's cache management
猜你喜欢

Deep understanding of read-write lock reentrantreadwritelock and concurrent container copyonwritearraylist

Tencent build project image

深入剖析Lock与AQS

Timer--

C language sanziqi, summed up a perfect SQL learning note in 22 days

3. Fiddler certificate installation and fetching hettps settings
Android 9,2022-2022字节跳动Android面试真题解析

An error is reported when reading the attribute value of the object through the variable storage key value in TS (TS: 7053)

LeetCode_63 不同路径 II

IT人不仅要提升挣钱能力,更要拓展挣钱途径,腾讯技术官发布的“神仙文档”火爆网络
随机推荐
Mariadb互为主从(双主模式)配置
error unable to access jarfile 解决方案
Brushless DC motor vector control (I): concept and process combing
万元礼品奖池!玩转「Lighthouse」有奖征文来袭
Advanced multithreading
Deep transfer learning
Knowledge is power, but more importantly, the ability to use knowledge - wechat code scanning payment on the web - technical design
Compared with redis, memcached
Apache IoTDB’s UDF源碼分析(1)
数据库SQL实战全解
我为什么那么爱用飞项做任务管理
MariaDB is configured as master-slave (dual master mode) to each other
Deep understanding of condition
In depth analysis of volatile principle
C language sanziqi, summed up a perfect SQL learning note in 22 days
链表 环形链表 链表判环 寻找入环节点141、142
Cloudera manager ha mode construction
HanderThread基本使用以及内部实现原理
Android 9,2022-2022字节跳动Android面试真题解析
知识就是力量,但更重要的是运用知识的能力---网页端微信扫码支付-技术设计