用c++实现以下代码:假设成立一个外包公司,主要给一些私营业主建网站。商家客户要求的功能包括信息发布、产品展示、博客留言等功能。 共有a-j 10个客户,其中a-c客户需要信息发布,d-f需要产品展示,g-j客户需要博客功能。 利用享元模式模拟该公司建立网站,输出如下: 客户a: 信息发布 客户b:信息发布 。。。 网站分类总数为:3
时间: 2024-02-06 19:11:19 浏览: 17
以下是用 C++ 实现的代码:
```cpp
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
// 网站分类接口
class Website {
public:
virtual void operation() = 0;
};
// 具体网站分类
class InformationWebsite : public Website {
public:
void operation() {
cout << "信息发布" << endl;
}
};
class ProductWebsite : public Website {
public:
void operation() {
cout << "产品展示" << endl;
}
};
class BlogWebsite : public Website {
public:
void operation() {
cout << "博客留言" << endl;
}
};
// 网站分类工厂
class WebsiteFactory {
public:
static Website* getWebsite(string type) {
auto it = websites.find(type);
if (it != websites.end()) {
return it->second;
} else {
Website* website = nullptr;
if (type == "information") {
website = new InformationWebsite();
} else if (type == "product") {
website = new ProductWebsite();
} else if (type == "blog") {
website = new BlogWebsite();
}
websites[type] = website;
return website;
}
}
private:
static unordered_map<string, Website*> websites;
};
unordered_map<string, Website*> WebsiteFactory::websites;
// 客户类
class Customer {
public:
Customer(string name, string type) : name(name), websiteType(type) {}
void useWebsite() {
cout << "客户" << name << ": ";
Website* website = WebsiteFactory::getWebsite(websiteType);
website->operation();
}
private:
string name;
string websiteType;
};
int main() {
Customer a("a", "information");
Customer b("b", "information");
Customer c("c", "information");
Customer d("d", "product");
Customer e("e", "product");
Customer f("f", "product");
Customer g("g", "blog");
Customer h("h", "blog");
Customer i("i", "blog");
Customer j("j", "blog");
a.useWebsite();
b.useWebsite();
c.useWebsite();
d.useWebsite();
e.useWebsite();
f.useWebsite();
g.useWebsite();
h.useWebsite();
i.useWebsite();
j.useWebsite();
cout << "网站分类总数为:" << WebsiteFactory::websites.size() << endl;
return 0;
}
```
输出结果:
```
客户a: 信息发布
客户b: 信息发布
客户c: 信息发布
客户d: 产品展示
客户e: 产品展示
客户f: 产品展示
客户g: 博客留言
客户h: 博客留言
客户i: 博客留言
客户j: 博客留言
网站分类总数为:3
```