文章目录
- 享元模式简介
- 结构
- UML图
- 具体实现
- UML图
- 代码实现
享元模式简介
- 享元模式(fly weight pattern)主要是通过共享对象来减少系统中对象的数量,其本质就是缓存共享对象,降低内存消耗。
- 享元模式将需要重复使用的对象分为两个状态:内部状态和外部状态,内部状态是不会变化的,可以被多个对象共享,而外部状态会随着对象的使用而改变。
- 实际中的使用:jdk-Interger(-128 127),存在于缓存池。
结构
- 1.抽象享元角色(FlyWeight):享元对象抽象基类或者接口,同事定义出对象的外部状态和内部状态的接口或实现;
- 2.具体享元角色(Concrete FlyWeight):实现抽象享元类中的方法,是需要共享的对象类。
- 3.享元工厂(FlyWeight Factory):维护一个享元对象的池,内部使用容器存储已经创建的享元对象。
UML图
具体实现
例子:从享元工厂类根据单车类型,获取对应的单车子类
UML图
代码实现
- 抽象享元类
package com.xxliao.pattern.structure.flyweight.demo;/*** @author xxliao* @description: 抽象享元类 FlyWeight , 单车类* @date 2024/5/25 17:17*/
public abstract class Bike {protected String color;protected float price;public Bike(String color, float price) {this.color = color;this.price = price;}/*** @description 打印单车信息* @author xxliao* @date 2024/5/25 17:19*/public abstract void print();
}
- 具体享元角色
package com.xxliao.pattern.structure.flyweight.demo;/*** @author xxliao* @description: 具体享元类 Concrete FlyWeight,* @date 2024/5/25 17:20*/
public class MoBike extends Bike{public MoBike(String color, float price) {super(color, price);}@Overridepublic void print() {System.out.println("生产成功:MoBike---"+color+",价格" + price + "元");}
}
package com.xxliao.pattern.structure.flyweight.demo;/*** @author xxliao* @description: 具体享元类 Concrete FlyWeight,* @date 2024/5/25 17:20*/
public class OfoBike extends Bike{public OfoBike(String color, float price) {super(color, price);}@Overridepublic void print() {System.out.println("生产成功:OfoBike---"+color+",价格" + price + "元");}
}
- 享元工厂
package com.xxliao.pattern.structure.flyweight.demo;import java.util.HashMap;
import java.util.Map;/*** @author xxliao* @description: 享元工厂* @date 2024/5/25 17:23*/
public class BikeFlyWeightFactory {// 缓存容器public static Map<String,Bike> bikeMap = new HashMap<>();// 获取享元对象public static Bike getBike(String color,String type) {String key = color + "-" + type;if(bikeMap.containsKey(key)) {// 已经在缓存容器中,直接返回return bikeMap.get(key);}else {// 缓存中没有,新建放入缓存中,然后返回Bike bike = null;if("mobike".equals(type)) {bike = new MoBike(color,199);}else if("ofobike".equals(type)) {bike = new OfoBike(color,199);}bikeMap.put(key,bike);return bike;}}
}
- 测试客户端
package com.xxliao.pattern.structure.flyweight.demo;/*** @author xxliao* @description: 享元模式 测试客户端* @date 2024/5/25 17:30*/
public class Client {public static void main(String[] args) {Bike bike1 = BikeFlyWeightFactory.getBike("橘色", "mobike");Bike bike2 = BikeFlyWeightFactory.getBike("黄色", "ofobike");bike1.print();bike2.print();System.out.println("======================================================");Bike bike3 = BikeFlyWeightFactory.getBike("黄色", "ofobike");System.out.println(BikeFlyWeightFactory.bikeMap.size());}
}
- 测试结果