设计模式——享元模式
2023-09-14 08:57:01 时间
Flyweight 直译为蝇量。就其表示的模式来说,翻译成享元,确实是不错的
package designpattern.structure.flyweight; public interface Flyweight { void action(int arg); } package designpattern.structure.flyweight; public class FlyweightImpl implements Flyweight { public void action(int arg) { // TODO Auto-generated method stub System.out.println("FlyweightImpl.action()"); } } package designpattern.structure.flyweight; import java.util.HashMap; import java.util.Map; public class FlyweightFactory { private static Map<String,Flyweight> flyweights = new HashMap<String,Flyweight>(); public FlyweightFactory(String arg) { flyweights.put(arg, new FlyweightImpl()); } public static Flyweight getFlyweight(String key) { if (flyweights.get(key) == null) { flyweights.put(key, new FlyweightImpl()); } return flyweights.get(key); } public static int getSize() { return flyweights.size(); } } package designpattern.structure.flyweight; public class Client { /** * * Fly微Weight量模式 —— 将小对象缓存起来的艺术。、、 * */ public static void main(String[] args) { Flyweight fly1 = FlyweightFactory.getFlyweight("a"); fly1.action(1); Flyweight fly2 = FlyweightFactory.getFlyweight("a"); System.out.println(fly1 == fly2); Flyweight fly3 =FlyweightFactory.getFlyweight("b"); fly3.action(2); Flyweight fly4 = FlyweightFactory.getFlyweight("c"); fly4.action(3); Flyweight fly5 =FlyweightFactory.getFlyweight("d"); fly4.action(4); System.out.println(FlyweightFactory.getSize()); } }
总结:
1 主要就是两个角色:a: 元或者说pojo角色—— 主要属性是其内部状态; b: 工厂角色,用来获取‘元’
2 ‘享’ 的具体实现是—— 工厂获取‘元’的时候,如果已经已经创建过,则直接取出返回;如果没,则创建并加入缓存,再返回
相关文章
- JS设计模式(一)-MODULE(模块模式)
- Servlet使用适配器模式进行增删改查案例(BaseServiceImplTest.java)
- C#设计模式——桥接模式(Bridge Pattern)
- 【设计模式】访问者模式
- iOS开发那些事-iOS常用设计模式–委托模式
- 「补课」进行时:设计模式(15)——观察者模式
- 《Android源码设计模式》--享元模式
- 《大话设计模式》--外观模式
- 【设计模式】享元模式
- Java设计模式之享元flyweight模式代码示例
- Atitit 前后端交互模式 目录 1.1. Ajax1 1.2. Fetch api1 1.3. 服务端脚本模式(简单快速)1 1.4. 浏览器注入对象、函数1 1.5. 浏览器插件模式
- C++设计模式:享元模式
- 【Java技巧 第6章】Java中BigDecimal 类的创建对象方法,介绍,常用方法以及8种舍入模式
- 实践GoF的23种设计模式:观察者模式
- 设计模式 Template Method模式 显示程序猿的一天
- 炒冷饭系列:设计模式 原型模式
- 003-结构型-02-装饰模式(Decorator)
- Javascript 的严格模式 use strict
- 外观模式
- 观察者模式
- 设计模式(Python语言)----适配器模式
- 设计模式python版(3)-工厂方法模式
- 设计模式python版(2)-简单工厂模式
- 我用过的设计模式(2)-- 单例模式
- 【设计模式】原型模式