1. 享元模式
比如围棋,10个棋子就需要实例化10个对象。这样导致内存空间浪费。 享元模式对于相同性质的棋子,会共享一个相同的对象,因此,围棋不管多少个棋子,只需要实例化黑白两个对象即可;
class Website {
public:
virtual void use() {}
};
class ConcreteWebsite :public Website {
private:
string name;
public:
ConcreteWebsite(const string& str) :name(str) {}
virtual void use() {
cout << "Website:" << name << endl;
}
};
class WebsiteFactory {
private:
map<string, Website*> websites;
public:
Website* getWebsite(const string& str) {
if (websites.find(str) == websites.end())
websites[str] = new ConcreteWebsite(str);
return websites[str];
}
};
int main(void) {
WebsiteFactory *f = new WebsiteFactory();
Website *fw1 = f->getWebsite("product");
Website *fw2 = f->getWebsite("product");
Website *fw3 = f->getWebsite("Blogs");
Website *fw4 = f->getWebsite("Blogs");
fw1->use();
fw2->use();
fw3->use();
fw4->use();
return 0;
}