1.享元模式概念
用于减少大量相似对象的内存消耗。通过共享尽可能多的数据来支持大量细粒度的对象,从而节省内存。
2.享元模式组成部分
1)享元接口 (Flyweight): 定义所有具体享元类的公共接口。
2)具体享元类 (Concrete Flyweight): 实现享元接口,并为内部状态存储内部数据。
3)非享元类 (Unshared Concrete Flyweight): 无法或不需要共享的对象。
4)享元工厂 (Flyweight Factory): 负责创建和管理享元对象,确保共享对象的正确管理。
3.举个栗子:
寝室有有一包卫生纸(享元对象),一包湿巾纸(享元对象)放在桌子上(享元工厂),用户(非享元对象)通过使用放在座子上的纸(享元接口)
如下图:
注:这个用缓存解释起来比较好,如果第一次访问某个静态资源,代理服务器(nginx),先看一下自己的缓存里面有没有这个资源,没有就问后端服务器要,向后端服务器要到之后在自己的本地缓存里面存一份,等到下次再有人访问这个请求时,代理服务器(nginx)看了一下自己的本地缓存里面有这个资源,就不用向后端服务器要资源,相当于这次请求走了(nginx)缓存,这样做减轻了后端服务器的压力
4.代码实现
1)享元接口
Paper 类
package org.xiji.Flyweight;/*** Flyweight享元接口** 卫生纸接口类*/
public interface Paper {/**** 使用卫生纸函数*/void use(String name);
}
2)享元对象
ToiletPaperImpl 卫生纸
package org.xiji.Flyweight;public class ToiletPaperImpl implements Paper{@Overridepublic void use(String name) {System.out.println(name+"使用了卫生纸");}}
WipesPaper 湿巾纸
package org.xiji.Flyweight;public class WipesPaper implements Paper{@Overridepublic void use(String name) {System.out.println(name+"使用了湿巾");}
}
3)享元工厂
PaperManger
package org.xiji.Flyweight;/*** 享元工厂***/
public class PaperManger {/*** 卫生纸*/ToiletPaperImpl toiletPaperImpl ;/*** 湿巾*/WipesPaper wipesPaper ;public Paper getInstance(String paperType) {if (paperType.equals("卫生纸")) {if (this.toiletPaperImpl == null) {this.toiletPaperImpl = new ToiletPaperImpl();}return this.toiletPaperImpl;}if (paperType.equals("湿巾")) {if (this.wipesPaper == null) {this.wipesPaper = new WipesPaper();}return this.wipesPaper;}return null;}}
4)客户端
FlyweightMain
package org.xiji.Flyweight;/*** 享元模式测试类*/
public class FlyweightMain {public static void main(String[] args) {String zhangSan = "张三";String xiaoJiu = "小久";String xiJi = "惜己";String liSi = "李四";//获取卫生纸PaperManger paperManger = new PaperManger();Paper toiletPaper = paperManger.getInstance("卫生纸");//获取湿巾Paper wipesPaper = paperManger.getInstance("湿巾");//使用toiletPaper.use(zhangSan);wipesPaper.use(xiaoJiu);toiletPaper.use(xiJi);wipesPaper.use(liSi);}
}