欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 设计模式之享元模式

设计模式之享元模式

2024/10/24 20:20:10 来源:https://blog.csdn.net/2301_76862031/article/details/141755905  浏览:    关键词:设计模式之享元模式

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);}
}

5)运行结果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com