图片引用于百度
简介:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。
优点:符合单一职责原则,很好的扩展性和灵活性
缺点:具体元素对访问者公布细节,违反了迪米特原则,具体元素变更比较困难
例子背景:现有小米商店和电脑商店,模拟顾客访问行为
访问者模式代码:
- 抽象商店类:
#pragma once
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Visitor;
using StoreList = vector<string>;
class Store
{
protected:
StoreList m_storeList;
public:
Store() {}
virtual ~Store() {}
public:
virtual void AcceptAccess(Visitor* v) = 0;
virtual StoreList GetCommodityList() { return m_storeList; }
};
- 具体商店类:
#pragma once
#include "Store.h"
class ComputerStore : public Store
{
public:
ComputerStore();
public:
virtual void AcceptAccess(Visitor* v);
};
class XiaoMiStore : public Store
{
public:
XiaoMiStore();
public:
virtual void AcceptAccess(Visitor* v);
};
- 具体商店cpp:
#include "Stores.h"
#include "Visitor.h"
ComputerStore::ComputerStore()
{
m_storeList = { "i3电脑主机", "i5电脑主机", "i7电脑主机", "i9电脑主机" };
}
void ComputerStore::AcceptAccess(Visitor* v)
{
v->AccessStore(this);
}
XiaoMiStore::XiaoMiStore()
{
m_storeList = { "小米11", "小米12", "小米12 Pro", "小米12 法拉利联名款" };
}
void XiaoMiStore::AcceptAccess(Visitor* v)
{
v->AccessStore(this);
}
- 抽象访问者类:
#pragma once
class Store;
class Visitor
{
public:
Visitor() {}
virtual ~Visitor() {}
public:
virtual void AccessStore(Store* s) = 0;
};
- 具体访问者类:
#pragma once
#include "Visitor.h"
class Customer : public Visitor
{
public:
Customer();
virtual void AccessStore(Store* s);
};
- 具体访问cpp:
#include "ConcreteVisitor.h"
#include "Store.h"
Customer::Customer()
{
}
void Customer::AccessStore(Store* s)
{
cout << "店铺有:" << endl;
for (auto iter : s->GetCommodityList())
{
cout << iter << " ";
}
cout << endl << "顾客购买了" << s->GetCommodityList().at(0) << endl;
}
- 引用:
#include "ConcreteVisitor.h"
#include "Stores.h"
int main()
{
shared_ptr<Customer> customer(new Customer);
shared_ptr<ComputerStore> computerStore(new ComputerStore);
shared_ptr<XiaoMiStore> xiaomiStore(new XiaoMiStore);
computerStore->AcceptAccess(customer.get());
xiaomiStore->AcceptAccess(customer.get());
getchar();
return 0;
}
总结:
访问者模式(Visitor):访问者主要实现将数据结构与数据操作分离,稳定的数据结构和易变的操作耦合问题
作者:丶梦爱
博客:https://blog.csdn.net/u014732297(转载请说明出处)