厦门市建设局网站摇号,飓风 网站建设,google浏览器官方,数字营销网站定义#xff1a;享元模式是一种结构型设计模式#xff0c;它使用共享对象#xff0c;用以尽可能减少内存使用和提高性能。享元模式通过共享已经存在的对象实例#xff0c;而不是每次需要时都创建新对象实例#xff0c;从而避免大量重复对象的开销。
对比#xff1a; 与单…定义享元模式是一种结构型设计模式它使用共享对象用以尽可能减少内存使用和提高性能。享元模式通过共享已经存在的对象实例而不是每次需要时都创建新对象实例从而避免大量重复对象的开销。
对比 与单例模式对比两者都限制了对象的创建不同之处在于单例模式全局只有一个实例而享元模式会在状态相同时共享同一个实例。 与原型模式对比虽然原型模式不涉及状态的共享但通过现有对象来创建一个新对象达到了新对象和原对象“内容”上的一致。在实现原型模式时根据场景也可以使用享元模式来优化对象的存储和创建过程。 代码
// 抽象享元角色
class Flyweight {
public:virtual ~Flyweight() default;virtual void display(const std::string extrinsicState) 0; // 外在状态作为参数传递
};// 具体享元角色
class ConcreteFlyweight : public Flyweight {
private:char intrinsicState; // 内在状态
public:ConcreteFlyweight(char state) : intrinsicState(state) {}void display(const std::string extrinsicState) override {std::cout Intrinsic State: intrinsicState , Extrinsic State: extrinsicState std::endl;}
};// 享元工厂角色
class FlyweightFactory {
private:std::unordered_mapchar, std::shared_ptrFlyweight flyweights;
public:std::shared_ptrFlyweight getFlyweight(char key) {if (flyweights.find(key) flyweights.end()) {flyweights[key] std::make_sharedConcreteFlyweight(key);}return flyweights[key];}
};// 客户端角色
class Client {
private:std::shared_ptrFlyweightFactory factory;
public:Client(std::shared_ptrFlyweightFactory f) : factory(f) {}void execute(char key, const std::string extrinsicState) {std::shared_ptrFlyweight flyweight factory-getFlyweight(key);flyweight-display(extrinsicState);}
};int main() {std::shared_ptrFlyweightFactory factory std::make_sharedFlyweightFactory();Client client(factory);client.execute(A, Position (10, 20));client.execute(B, Position (15, 25));client.execute(A, Position (20, 30)); // A 是共享的所以使用相同的实例return 0;
}