classTree { int x_; int y_; std::shared_ptr<TreeType> type_; // 享元模式的核心。type_在相同种类的树之间是共享的。此处必须使用指针,而不是实例!否则存储的将是副本,而不是共享对象。 public: Tree(int x, int y, std::shared_ptr<TreeType> type): x_(x), y_(y), type_(type) {} voiddraw(const Canvas& c){ type_->draw(c, x_, y_); } }
classForest { std::vector<Tree> trees_; voidplantTree(int x, int y, std::string name, std::string color, std::string texture){ auto type = TreeFactory::getTreeType(name, color, texture); Tree tree = Tree(x, y, type); trees_.push_back(tree); } voiddraw(const Canvas& c){ for (int i = 0; i < trees_.size(); i++) trees_[i].draw(c); } }