简述:
享元模式:运用共享技术有效地支持大量细粒度的对象。
享元模式包括:享元工厂类、享元接口类、具体享元类
享元工厂类: 用来创建并管理享元接口类对象,它主要是用来确保合理地共享享元接口类,当用户请求一个享元接口类对象时,享元工厂类对象提供一个已创建的实例或者创建一个(不存在的话)
享元接口类:所有具体享元类的超类或接口,通过这个接口可以接受并作用于外部状态。
具体享元类:继承享元接口超累或实现享元接口类接口,并为内部状态增加存储空间
不共享具体享元类:指那些不需要共享的享元接口类的子类,因为享元接口类共享成为可能,但它并不强制共享。
应用场景:如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时,就应该考虑使用;还有就是对象大多数状态可以是外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式
注:开发环境调整为VS2017,操作系统win11
享元模式:
1 #include
2 #include
输出结果:
例:网站共享代码
代码如下:
1 #include
2 #include
输出结果: