C++设计模式学习之一(共计13种)

这篇具有很好参考价值的文章主要介绍了C++设计模式学习之一(共计13种)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1)简单工厂模式

#include <iostream>
#include <memory>
//简单工厂模式
//产品基类
class Productor
{
public:
	virtual void doWork(void) = 0;
};
//产品A
class ProductorA : public Productor
{
public:
	virtual void doWork(void) override
	{
		printf("ProductorA output\r\n");
	}
};
//产品B
class ProductorB : public Productor
{
public:
	virtual void doWork(void) override
	{
		printf("ProductorB output\r\n");
	}
};
//工厂基类
class Factory
{
public:
	virtual std::unique_ptr<Productor> CreateProduct() = 0;
};
//工厂A
class DerivedCreateA : public Factory
{
public:
	virtual std::unique_ptr<Productor> CreateProduct()
	{
		return std::make_unique<ProductorA>();
	}
};
//工厂B
class DerivedCreateB : public Factory
{
public:
	virtual std::unique_ptr<Productor> CreateProduct()
	{
		return std::make_unique<ProductorB>();
	}
};
int main(void)
{
	//创建工厂A
	DerivedCreateA fa;
	auto pa = fa.CreateProduct(); //产出pa产品
	pa->doWork(); //执行a产品的工作函数
	//创建工厂B
	DerivedCreateB fb;
	auto pb = fb.CreateProduct(); //产出pb产品
	pb->doWork(); //执行b产品的工作函数
	return 0;
}

2)builder-建造者模式

#include<iostream>
#include<string>
#include<vector>

using namespace std;
//抽象产品类
class AbstractProduct
{
public:
	virtual void setDisplayer(string displayer) = 0;
	virtual void setHost(string host) = 0;
	virtual void setKeyBoard(string keyboard) = 0;
	virtual void setMouse(string mouse) = 0;
	virtual void showConfig(void) = 0;
};
//具体产品类
class Computer : public AbstractProduct
{
public:
	virtual void setDisplayer(string displayer)
	{
		_list.push_back(displayer);
	}
	virtual void setHost(string host)
	{
		_list.push_back(host);
	}
	virtual void setKeyBoard(string keyboard)
	{
		_list.push_back(keyboard);
	}
	virtual void setMouse(string mouse)
	{
		_list.push_back(mouse);
	}
	virtual void showConfig(void)
	{
		cout << "computer config is" << endl;
		for (auto e : _list)
		{
			cout << e << endl;
		}
	}
	vector<string> _list;
};
//抽象建造者类
class AbstractBuilder
{
public:
	AbstractBuilder(): product(new Computer){}
	//抽象构造过程
	virtual void BuildDisplayer(string display) = 0;
	virtual void BuildMouse(string mouse) = 0;
	virtual void BuildKeyBoard(string keyBoard) = 0;
	virtual void BuildHost(string host) = 0;
	AbstractProduct* Getproduct()
	{
		return product;
	}
protected:
	AbstractProduct* product;
};
//具体建造者
class ConcreteBuilder : public AbstractBuilder
{
public:
	virtual void BuildDisplayer(string display)override
	{
		product->setDisplayer(display);
	}
	virtual void BuildMouse(string mouse)override
	{
		product->setMouse(mouse);
	}
	virtual void BuildKeyBoard(string keyBoard)override
	{
		product->setKeyBoard(keyBoard);
	}
	virtual void BuildHost(string host)override
	{
		product->setHost(host);
	}
};
//指挥者类
class Director
{
public:
	Director(AbstractBuilder* pBuilder):_pBuilder(pBuilder){}
	AbstractProduct* createProduct(string displayer, string mouse, string keyboard, string host)
	{
		_pBuilder->BuildDisplayer(displayer);
		_pBuilder->BuildMouse(mouse);
		_pBuilder->BuildKeyBoard(keyboard);
		_pBuilder->BuildHost(host);
		return _pBuilder->Getproduct();
	}
private:
	AbstractBuilder* _pBuilder;
};
int main(void)
{
	AbstractBuilder* pb = new ConcreteBuilder;
	Director* pd = new Director(pb);
	AbstractProduct* computer = pd->createProduct("华为显示器", "牧马人鼠标", "雷蛇键盘", "外星人");
	computer->showConfig();
	return 0;
}

3)prototype-原型模式

#include <iostream>
#include <memory>
#include <string>
using namespace std;

class Monkey
{
public:
	Monkey() = default;
	virtual ~Monkey(){}
	virtual Monkey* Clone() = 0;
	virtual void Play() = 0;
};
//2变化
class SunWuKong : public Monkey
{
public:
	SunWuKong(string name) : _name(name){}
	SunWuKong(const SunWuKong& obj)
	{
		_name = obj._name;
	}
	Monkey* Clone()
	{
		//调用拷贝构造函数,目前用的是浅拷贝
		return new SunWuKong(*this);
	}
	virtual void Play()
	{
		cout << _name << ",玩金箍棒" << endl;
	}
private:
	string _name;
};
int main(void)
{
	Monkey* monkey = new SunWuKong("齐天大圣");
	Monkey* monkey1 = monkey->Clone();
	Monkey* monkey2 = monkey->Clone();
	monkey->Play();
	monkey1->Play();
	monkey2->Play();
	delete monkey;
	delete monkey1;
	delete monkey2;

	return 0;
}

4)proxy-代理模式

#include <iostream>
#include <memory>
#include <string>
using namespace std;

/*
1.提供一个抽象主题角色:真实主题和代理主题的共同接口;
2.提供一个真实主题角色:定义了代理角色所代表的真实对象;
3.提供一个代理主题角色:含有对真实主题角色的引用;
*/

class AbstractObj
{
public:
	virtual void BuyTicket() = 0;
};
class User : public AbstractObj
{
public:
	void BuyTicket()override
	{
		cout << "用户买票" << endl;
	}
};
class XiCheng : public AbstractObj
{
public:
	XiCheng(AbstractObj* pBase)
	{
		_pBase = pBase;
	}
	void BuyTicket()override
	{
		cout << "携程买票" << endl;
	}
private:
	AbstractObj* _pBase;
};
int main(void)
{
	AbstractObj* pbase = new User;
	pbase->BuyTicket(); //用户买票
	XiCheng* pProxy = new XiCheng(pbase);
	pProxy->BuyTicket(); //代理购票
	return 0;
}

//代理案例2
#include <iostream>
using namespace std;
//抽象主题类
class AbstractSubject
{
public:
	virtual void request() = 0;
};
//具体主题类
class ConcreteSubject : public AbstractSubject
{
public:
	void request()override
	{
		std::cout << "真实主题类请求" << endl;
	}
};
//代理类
class Proxy : public AbstractSubject
{
private:
	ConcreteSubject* realSubject; //这个是具体类
public:
	Proxy()
	{
		realSubject = new ConcreteSubject();
	}
	~Proxy()
	{
		delete realSubject;
	}
	void request()override
	{
		//在调用真实主题类的请求之前或者之后,可以进行一些额外的操作
		std::cout << "代理类的请求" << endl;
		realSubject->request();
	}
};

int main(void)
{
	Proxy proxy; //创建代理对象
	proxy.request(); //调用代理对象的请求,间接的调用了真实主题类的请求;
	return 0;
}

5)decorate-装饰器模式

#include <iostream>
#include<string>

using namespace std;

/*
提供一个抽象组件类:抽象被装饰者的行为
提供一个或多个具体组件类:被装饰者的具体行为实现
提供一个抽象装饰器类:
提供一个具体的装饰器类:为具体组件附加责任;
*/
//抽象组件类
class AbstractCompent
{
public:
	virtual void show() = 0;
	string _pStr;
};
//具体组件类
class Girl : public AbstractCompent
{
public:
	Girl()
	{
		_pStr = "啥也没穿的女孩子";
	}
	virtual void show()override
	{
		cout << _pStr << endl;
	}
};
//抽象装饰器类
class AbstractDecorate : public AbstractCompent
{
public:
	virtual void show() = 0;
protected:
	AbstractCompent* _pBase;
};
//具体装饰器类(超短裙)
class MiniSkirt : public AbstractDecorate
{
public:
	MiniSkirt(AbstractCompent* pbase)
	{
		_pBase = pbase;
	}
	void show(void)override
	{
		this->_pStr = this->_pBase->_pStr + " 超短裙";
		cout << _pStr << endl;
	}
};
//具体装饰器类(黑丝)
class BlackSilk : public AbstractDecorate
{
public:
	BlackSilk(AbstractCompent* pbase)
	{
		_pBase = pbase;
	}
	void show(void)override
	{
		this->_pStr = this->_pBase->_pStr + " 黑丝";
		cout << _pStr << endl;
	}
};

int main(void)
{
	//啥也没穿
	Girl* pG = new Girl;
	pG->show();
	//穿超短裙
	MiniSkirt* pM = new MiniSkirt(pG);  //装饰的是主体(pG)组件
	pM->show();
	//穿黑丝
	BlackSilk* pB = new BlackSilk(pG);  //装饰的是主体(pG)组件
	pB->show();
	//穿超短裙和黑丝
	BlackSilk* pB1 = new BlackSilk(pM); //装饰的是非主体(pM)组件
	pB1->show();
	return 0;
}

6)adapter-适配器模式

1)对象做适配
#include <iostream>
#include<string>
using namespace std;

//电源插座
class ThreeOutlet
{
public:
	void ThreeOutletCharge()
	{
		cout << "开始三插头充电" << endl;
	}
};

class AbstractTwoOutlet
{
public:
	virtual void TwoOutletcharge() = 0;
};

class TwoOutlet : public AbstractTwoOutlet
{
public:
	virtual void TwoOutletcharge()override
	{
		cout << "客户需要两插头充电............" << endl;
	}
};
//对象做适配
class OutletAdapterObject : public AbstractTwoOutlet
{
public:
	OutletAdapterObject(ThreeOutlet* pout)
	{
		this->_pOut = pout;
	}
	virtual void TwoOutletcharge()
	{
		convertor();
		_pOut->ThreeOutletCharge();
	}
	void convertor()
	{
		cout << "三插头转换为两插头" << endl;
	}
protected:
	ThreeOutlet* _pOut;
};
int main(void)
{
	ThreeOutlet* pThree = new ThreeOutlet;
	pThree->ThreeOutletCharge();
	AbstractTwoOutlet* pTwo = new OutletAdapterObject(pThree);
	pTwo->TwoOutletcharge();
	return 0;
}


2)类做适配(采用多继承方式)
#include <iostream>
#include<string>
using namespace std;

//电源插座
class ThreeOutlet
{
public:
	void ThreeOutletCharge()
	{
		cout << "开始三插头充电" << endl;
	}
};

class AbstractTwoOutlet
{
public:
	virtual void TwoOutletcharge() = 0;
};

class TwoOutlet : public AbstractTwoOutlet
{
public:
	virtual void TwoOutletcharge()override
	{
		cout << "客户需要两插头充电............" << endl;
	}
};
//针对类做适配
class OutletAdapterClass : public AbstractTwoOutlet,public ThreeOutlet
{
public:
	void TwoOutletcharge()
	{
		convertor();
		ThreeOutletCharge();
	}
	void convertor()
	{
		cout << "三插头转换为两插头" << endl;
	}
protected:
	ThreeOutlet* _pOut;
};
int main(void)
{
	ThreeOutlet* pThree = new ThreeOutlet;
	pThree->ThreeOutletCharge();
	AbstractTwoOutlet* pTwo = new OutletAdapterClass;
	pTwo->TwoOutletcharge();
	return 0;
}

7)bridge-桥接模式

#include <iostream>
#include<string>
using namespace std;

class AbstractColor
{
public:
	virtual void FillColor() = 0;
};
class Red : public AbstractColor
{
public:
	Red(): _colorType("red") {}
	void FillColor()
	{
		cout << "填充颜色:" << _colorType << endl;
	}
private:
	string _colorType;
};
class Blue : public AbstractColor
{
public:
	Blue() : _colorType("Blue") {}
	void FillColor()
	{
		cout << "填充颜色:" << _colorType << endl;
	}
private:
	string _colorType;
};

class AbstractShape
{
public:
	virtual void ShowShape() = 0;
	virtual void SetColor(AbstractColor* color) = 0;
protected:
	virtual void DrawShape() = 0;
	virtual void DrawColor() = 0;
	AbstractColor* _color;
};
class Circle : public AbstractShape
{
public:
	Circle() : _shapeType("circle") {}
	void ShowShape()override
	{
		DrawShape();
		DrawColor();
	}
	void SetColor(AbstractColor* color)override
	{
		this->_color = color;
	}
private:
	virtual void DrawShape()override
	{
		cout << "绘制: " << _shapeType << endl;
	}
	virtual void DrawColor()override
	{
		this->_color->FillColor();
	}
	string _shapeType;
};
class Rect : public AbstractShape
{
public:
	Rect():_shapeType("rect"){}
	void ShowShape()override
	{
		DrawShape();
		DrawColor();
	}
	void SetColor(AbstractColor* color)override
	{
		this->_color = color;
	}
private:
	virtual void DrawShape()override
	{
		cout << "绘制: " << _shapeType << endl;
	}
	virtual void DrawColor()override
	{
		this->_color->FillColor();
	}
	string _shapeType;
};
int main(void)
{
	cout << "绘制红色的圆" << endl;
	AbstractShape* shape = new Circle;
	shape->SetColor(new Red);
	shape->ShowShape(); //红色的圆
	delete shape;
	cout << endl;
	cout << "绘制蓝色的矩形" << endl;
	AbstractShape* rect = new Rect;
	rect->SetColor(new Blue);
	rect->ShowShape(); //蓝色的矩形
	delete rect;
	return 0;
}

8)facade-外观者模式

#include<iostream>
#include<string>

using namespace std;
//功能提供者类,包括CsyntaxParse,CMidCode,CAssemblyCode,CLinkFile;
class CsyntaxParse
{
public:
	void syntaxParse()
	{
		cout << "语法分析中..." << endl;
	}
};
class CMidCode
{
public:
	void MidCode()
	{
		cout << "生成中间文件代码中..." << endl;
	}
};
class CAssemblyCode
{
public:
	void AssemblyCode()
	{
		cout << "生成汇编代码中..." << endl;
	}
};
class CLinkFile
{
public:
	void LinkFile()
	{
		cout << "连接文件,生成可执行程序......" << endl;
	}
};

class Facade
{
public:
	void Build() //做了一些表面工作
	{
		CsyntaxParse p;
		CMidCode m;
		CAssemblyCode a;
		CLinkFile c;
		p.syntaxParse();
		m.MidCode();
		a.AssemblyCode();
		c.LinkFile();
		cout << "程序运行。。。" << endl;
	}
};
//对客户来说,只使用外观者类即可;
int main(void)
{
	Facade obj; //上帝对象
	obj.Build();
	return 0;
}

9)flyweight-享元模式

/**
 * 享元设计
 *
 *享元:就是共享元素的意思;
 * 目的: 通过共享多个对象之间的公共状态而不保存每个对象中的所有数据,以将更多的对象放入可用的RAM中
 */
#include<iostream>
#include<string>
#include<unordered_map>

struct SharedState
{
    std::string brand_;
    std::string model_;
    std::string color_;

    SharedState(const std::string& brand, const std::string& model, const std::string& color)
        : brand_(brand), model_(model), color_(color)
    {
    }

    friend std::ostream& operator<<(std::ostream& os, const SharedState& ss)
    {
        return os << "[ " << ss.brand_ << " , " << ss.model_ << " , " << ss.color_ << " ]";
    }
};

struct UniqueState
{
    std::string owner_;
    std::string plates_;

    UniqueState(const std::string& owner, const std::string& plates)
        : owner_(owner), plates_(plates)
    {
    }

    friend std::ostream& operator<<(std::ostream& os, const UniqueState& us)
    {
        return os << "[ " << us.owner_ << " , " << us.plates_ << " ]";
    }
};

/**
 * Flyweight存储属于多个实际业务实体的公共状态部分(也称为内在状态)。
 * 通过成员函数的参数接受状态的其余部分(外部状态,每个实体都是惟一的)。
 */
class Flyweight
{
private:
    SharedState* shared_state_;

public:
    Flyweight(const SharedState* shared_state) : shared_state_(new SharedState(*shared_state))
    {
    }
    Flyweight(const Flyweight& other) : shared_state_(new SharedState(*other.shared_state_))
    {
    }
    ~Flyweight()
    {
        delete shared_state_;
    }
    SharedState* shared_state() const
    {
        return shared_state_;
    }
    void Operation(const UniqueState& unique_state) const
    {
        std::cout << "Flyweight: Displaying shared (" << *shared_state_ << ") and unique (" << unique_state << ") state.\n";
    }
};
/**
 * Flyweight Factory创建和管理Flyweight对象,确保flyweight的用法和样例:当客户请求享元时,
 * 工厂要么返回一个现有实例(如果有的话),要么创建一个新实例。
 */
class FlyweightFactory
{
    /**
     * @var Flyweight[]
     */
private:
    std::unordered_map<std::string, Flyweight> flyweights_;
    /**
     * 返回对应状态的享元的键名。
     */
    std::string GetKey(const SharedState& ss) const
    {
        return ss.brand_ + "_" + ss.model_ + "_" + ss.color_;
    }

public:
    FlyweightFactory(std::initializer_list<SharedState> share_states)
    {
        for (const SharedState& ss : share_states)
        {
            this->flyweights_.insert(std::make_pair<std::string, Flyweight>(this->GetKey(ss), Flyweight(&ss)));
        }
    }

    /**
     * 返回具有给定状态的Flyweight或创建一个新Flyweight。
     */
    Flyweight GetFlyweight(const SharedState& shared_state)
    {
        std::string key = this->GetKey(shared_state);
        if (this->flyweights_.find(key) == this->flyweights_.end())
        {
            std::cout << "FlyweightFactory: Can't find a flyweight, creating new one.\n";
            this->flyweights_.insert(std::make_pair(key, Flyweight(&shared_state)));
        }
        else
        {
            std::cout << "FlyweightFactory: Reusing existing flyweight.\n";
        }
        return this->flyweights_.at(key);
    }
    void ListFlyweights() const
    {
        size_t count = this->flyweights_.size();
        std::cout << "\nFlyweightFactory: I have " << count << " flyweights:\n";
        for (std::pair<std::string, Flyweight> pair : this->flyweights_)
        {
            std::cout << pair.first << "\n";
        }
    }
};

// ...
void AddCarToPoliceDatabase(
    FlyweightFactory& ff, const std::string& plates, const std::string& owner,
    const std::string& brand, const std::string& model, const std::string& color)
{
    std::cout << "\nClient: Adding a car to database.\n";
    const Flyweight& flyweight = ff.GetFlyweight({ brand, model, color });
    // 客户端代码存储或计算外部状态并将其传递给享元对象的成员函数。
    flyweight.Operation({ owner, plates });
}

/**
 * 客户端代码通常在应用程序的初始化阶段创建一堆预先填充的权重值。
 */
int main()
{
    FlyweightFactory* factory = new FlyweightFactory({ {"Chevrolet", "Camaro2018", "pink"}, {"Mercedes Benz", "C300", "black"}, {"Mercedes Benz", "C500", "red"}, {"BMW", "M5", "red"}, {"BMW", "X6", "white"} });
    factory->ListFlyweights();

    AddCarToPoliceDatabase(*factory,
        "CL234IR",
        "James Doe",
        "BMW",
        "M5",
        "red");

    AddCarToPoliceDatabase(*factory,
        "CL234IR",
        "James Doe",
        "BMW",
        "X1",
        "red");
    factory->ListFlyweights();
    delete factory;

    return 0;
}

10)composite-组合模式

#include<iostream>
#include<string>
#include<list>

using namespace std;

class Root
{
public:
	virtual void display(void) = 0;
	virtual void add(Root* file) = 0;
	virtual void remove(Root* file) = 0;
	virtual list<Root*> getchild() = 0;
};

class File : public Root
{
public:
	File(string name):_name(name){}
	virtual void display(void)override { cout << _name << endl; }
	virtual void add(Root* file)override {}
	virtual void remove(Root* file)override {}
	virtual list<Root*> getchild()override
	{
		return _list;
	}
protected:
	string _name;
	list<Root*>_list;
};

class Floder : public Root
{
private:
	list<Root*> _list;
	string _name;
public:
	Floder(string name) :_name(name) {}
	virtual void display(void)override { cout << _name << endl; }
	virtual void add(Root* file)override 
	{
		_list.push_back(file);
	}
	virtual void remove(Root* file)override
	{
		_list.push_back(file);
	}
	virtual list<Root*> getchild()override
	{
		return _list;
	}
};
//统一一个接口
void ShowTree(Root* file, int level)
{
	list<Root*> root;
	int i = 0;
	for (int i = 0; i < level; i++)
	{
		cout << "--";
	}
	file->display();
	root = file->getchild();
	if (!root.empty())
	{
		for (auto e : root)
		{
			if (e->getchild().empty())
			{
				for (int i = 0; i <= level; i++)
				{
					cout << "--";
				}
				e->display();
			}
			else
			{
				ShowTree(e, level + 1);
			}
		}
	}
}

int main(void)
{
	Floder* root = new Floder("C:");
	Floder* d1 = new Floder("dir1");
	File* f1 = new File("t1.txt");

	Floder* d2 = new Floder("dir2");
	File* f2 = new File("t2.txt");

	root->add(d1);
	root->add(d2);
	d1->add(f1);
	d2->add(f2);
	ShowTree(root, 0);
	return 0;
}

11)templateMethod-模板方法模式

#include<iostream>
#include<string>
using namespace std;

class Makeobject
{
public:
	virtual void Makehead() = 0;
	virtual void Makebody() = 0;
	virtual void Garb() = 0;
	void Make()
	{
		Makehead();
		Makebody();
		Garb(); //服装
	}
};
class MakeGirl : public Makeobject
{
public:
	virtual void Makehead()
	{
		cout << "刘亦菲的头" << ",";
	}
	virtual void Makebody()
	{
		cout << "杨梅的身材" << ",";
	}
	virtual void Garb()
	{
		cout << "穿古装" << endl;
	}
};

class MakeBoy : public Makeobject
{
public:
	virtual void Makehead()
	{
		cout << "胡哥的头" << ",";
	}
	virtual void Makebody()
	{
		cout << "姜小二身材" << ",";
	}
	virtual void Garb()
	{
		cout << "穿西装---" << endl;
	}
};

int main(void)
{
	Makeobject* pobj = new MakeGirl;
	pobj->Make();
	delete pobj;
	pobj = new MakeBoy;
	pobj->Make();
	delete pobj;
	return 0;
}

12)Command-命令模式

#include<iostream>
#include<vector>
#include<string>
using namespace std;
//命令模式:服务员点菜及厨师做菜为案例
//定义厨师类
class Cook
{
public:
	void MakeVegetable()
	{
		cout << "蔬菜沙拉一份" << endl;
	}
	void MakeSteak()
	{
		cout << "牛排一份" << endl;
	}
	void UnVegetable()
	{
		cout << "蔬菜沙拉不要了" << endl;
	}
	void UnSteak()
	{
		cout << "牛排不要了" << endl;
	}
};
//抽象命令类
class Command
{
public:
	Command(Cook* cook = nullptr) : _cook(cook){}
	virtual void ExecuteCommand() = 0;
	virtual void UnExecuteCommand() = 0;
protected:
	Cook* _cook;
};
//具体命令类(做蔬菜沙拉)
class ConcreteVegetableCommand : public Command
{
public:
	ConcreteVegetableCommand(Cook* cook) : Command(cook){} //子类初始化父类
	void ExecuteCommand()override
	{
		_cook->MakeVegetable();
	}
	void UnExecuteCommand()override
	{
		_cook->UnVegetable();
	}
};
//具体命令类(做牛排)
class ConcreteSteakCommand : public Command
{
public:
	ConcreteSteakCommand(Cook* cook) : Command(cook) {} //子类初始化父类
	void ExecuteCommand()override
	{
		_cook->MakeSteak();
	}
	void UnExecuteCommand()override
	{
		_cook->UnSteak();
	}
};
//客户点菜
class Order
{
public:
	void setOrder(Command* cmd)
	{
		_cmdQueue.push_back(cmd);
		cout << "点一道菜" << endl;
	}
	void unOrder(Command* cmd)
	{
		_cmdQueue.pop_back(); //这里可以用查找功能,删除具体的命令,目前没有实现
		cout << "不要一道菜" << endl;
	}
	void Notify()
	{
		for (auto e : _cmdQueue)
		{
			e->ExecuteCommand();
		}
	}
private:
	vector<Command*> _cmdQueue;
};
int main(void)
{
	Cook* pcook = new Cook;
	Command* pvegetable = new ConcreteVegetableCommand(pcook);
	Command* pSteak = new ConcreteSteakCommand(pcook);
	Order* porder = new Order;
	//订单推送到命令队列
	porder->setOrder(pvegetable);
	porder->setOrder(pSteak);
	porder->Notify();
	cout << endl;
	//中途可以不要一道菜,如把牛排推掉
	porder->unOrder(pSteak);
	porder->Notify();
	cout << endl;
	//中途又加上一道菜,如把牛排推掉
	porder->setOrder(pSteak);
	porder->Notify();
	return 0;
}

/*
输出结果:
点一道菜
点一道菜
蔬菜沙拉一份
牛排一份

不要一道菜
蔬菜沙拉一份

点一道菜
蔬菜沙拉一份
牛排一份
*/

13)reposiblitychain-责任链模式文章来源地址https://www.toymoban.com/news/detail-755169.html

#include<iostream>
#include<string>
using namespace std;
//抽象一个处理的类
class Handler
{
public:
	Handler(): _pNext(nullptr){}
	//转接下一位
	void SetNextHandler(Handler* pnext)
	{
		this->_pNext = pnext;
	}
	//具体请求
	virtual void HandlerRequest(int days) = 0;
protected:
	Handler* _pNext;
};
//以下三个类为具体处理着
class Director:public Handler
{
public:
	virtual void HandlerRequest(int days)override
	{
		cout << "主管回复:";
		if (days <= 1)
		{
			cout << "主管同意请假" << endl;
		}
		else
		{
			cout <<"请假太长,找经理请假" << endl;
			_pNext->HandlerRequest(days);
		}
	}
};
class Manager :public Handler
{
public:
	virtual void HandlerRequest(int days)override
	{
		cout << "经理回复:";
		if (days <= 3)
		{
			cout << "经理同意请假" << endl;
		}
		else
		{
			cout << "请假太长,找老板请假" << endl;
			_pNext->HandlerRequest(days);
		}
	}
};
class Boss :public Handler
{
public:
	virtual void HandlerRequest(int days)override
	{
		cout << "老板回复:";
		if (days <= 7)
		{
			cout << "老板同意请假" << endl;
		}
		else
		{
			cout << "请假太长,不予批准!" << endl;
		}
	}
};

int main(void)
{
	//组装链
	Handler* pdirector = new Director;
	Handler* pmanager = new Manager;
	Handler* pboss = new Boss;
	pdirector->SetNextHandler(pmanager);
	pmanager->SetNextHandler(pboss);
	//开始测试请假
	cout << "请假1天结果......" << endl;
	pdirector->HandlerRequest(1);
	cout << "请假2天结果......" << endl;
	pdirector->HandlerRequest(2);
	cout << "请假8天结果......" << endl;
	pdirector->HandlerRequest(8);
	delete pdirector;
	delete pmanager;
	delete pboss;
	return 0;
}

到了这里,关于C++设计模式学习之一(共计13种)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • PO设计模式是selenium自动化测试中最佳的设计模式之一

    Page Object Model:PO设计模式是selenium自动化测试中最佳的设计模式之一,主要体现在对界面交互细节的封装,也就是在实际测试中只关注业务流程就OK了传统的设计中,在新增测试用例之后,代码会有以下几个问题:1.易读性差:一连串的find element会使代码显得杂乱无章2.可扩展

    2024年02月11日
    浏览(41)
  • 设计模式(13):模板方法模式

    实现一个功能时,整体步骤很固定,但是,某些部分易变。易变部分可以抽象出来,供子类实现。 非常繁琐,各个框架,类库中都有它的影子,比如常见的有: 数据库访问的封装 Junit单元测试 servlet中关于doGet/doPost方法调用 spring框架中各种Template shire中权限认证和授权都用到

    2024年04月16日
    浏览(45)
  • 【python设计模式】13、策略模式

    哲学思想: 策略模式是一种设计模式,它可以使得我们在程序中根据需要动态地选择算法的具体实现方式。策略模式的思想源于哲学中的“多元论”(pluralism)和“实用主义”(pragmatism)。 多元论认为,世界上存在着许多不同的观点和方法,没有一个固定的标准或者方法是

    2023年04月08日
    浏览(41)
  • 研磨设计模式day13组合模式

    目录 场景 不用模式实现  代码实现  有何问题  解决方案 代码改造  组合模式优缺点 思考  何时选用 场景 不用模式实现  代码实现  叶子对象 组合对象 Client 有何问题  必须区分组合对象和叶子对象,并进行有区别的对待 解决方案 组合模式 定义: 思路:将组合对象和叶

    2024年02月11日
    浏览(40)
  • Java 与设计模式(13):代理模式

    代理模式是一种结构型设计模式,用于在访问对象时引入一个代理对象,以控制对实际对象的访问。代理对象充当了客户端和实际对象之间的中介,客户端通过代理对象间接地访问实际对象,从而可以在访问过程中添加额外的逻辑或控制。代理模式可以提供对实际对象的保护

    2024年02月09日
    浏览(37)
  • 经典的设计模式13——模板方法模式

    开始11个属于行为型模式的复习。 用户登录控制功能用模板方法实现。 定义: 定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。 结构: 抽象类(abstract):负责给出一个算法的轮廓和骨架

    2024年02月08日
    浏览(37)
  • 笨蛋学设计模式结构型模式-享元模式【13】

    7.7.1概念 ​ 享元模式是通过共享对象减少内存使用,来提高程序性能。在此模式中,分为内部状态和外部状态,其中相似的对象被存储在享元对象内部,并对于所有享元对象都是相同的,且状态通常是不变的。只在需要时内部共享,而不是每次创建新的对象。而外部状态是享

    2024年01月23日
    浏览(43)
  • 【设计模式】第13节:结构型模式之“享元模式”

    所谓“享元”,顾名思义就是被共享的单元。享元模式的意图是复用对象,节省内存,前提是享元对象是不可变对象。 实现:通过工厂模式,在工厂类中,通过一个Map或者List来缓存已经创建好的享元对象,以达到复用的目的。把实例的共享状态和不共享状态分开。 以下是画

    2024年02月08日
    浏览(41)
  • 一文带你通俗理解23种软件设计模式(推荐收藏,适合小白学习,附带C++例程完整源码)

    作者:翟天保Steven 版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处        设计模式是为了解决在软件开发过程中遇到的某些问题而形成的思想。同一场景有多种设计模式可以应用,不同的模式有各自的优缺点,开发者可以基于自身需求

    2024年02月09日
    浏览(53)
  • 【设计模式】Head First 设计模式——策略模式 C++实现

    设计模式最大的作用就是在变化和稳定中间寻找隔离点,然后分离它们,从而管理变化。将变化像小兔子一样关到笼子里,让它在笼子里随便跳,而不至于跳出来把你整个房间给污染掉。 将行为想象为一族算法,定义算法族,分别封装起来,让他们之间可以互相替换,使得算

    2024年02月11日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包