结构型模式之享元模式FlyWeight

mac2024-05-12  30

享元模式FlyWeight

1.使用场景

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。 如果有很多完全相同或部分相同的对象,我们可以通过享元模式节省内存。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。 如:线程池,数据库连接池

2.核心

在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建 享元模式以共享的方式高效地支持大量细粒度对象的重用 享元对象能做到共享的关键是区分了内部状态和外部状态

内部状态:可以共享,不会随时间改变而改变外部状态:不可以共享,会随时间改变而改变

3.实现

3.1FlyWeight抽象享元类:通常是一个接口或抽象类,声明公共方法。向外部提供对象的内部状态,设置内部状态
3.2ConcreteFlyWeight具体享元类
3.3UnSharedConcreteFlyWeight非共享享元类
3.4 FlyWeightFactory享元工厂,用 HashMap 存储这些对象。创建管理享元类
package com.liang.flyWeight; /** * FlyWeight抽象享元类 * @author Administrator * */ public interface ChessFlyWeight { String getColor(); void disPlsy(Coordinate c); } package com.liang.flyWeight; /** * UnSharedConcreteFlyWeight非共享享元类 * 坐标,外部状态 * @author Administrator * */ public class Coordinate { private int x,y; public Coordinate(int x, int y) { super(); this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } package com.liang.flyWeight; /** * ConcreteFlyWeight具体享元类 * @author Administrator * */ public class ConcreteChess implements ChessFlyWeight { private String color; public ConcreteChess(String color) { this.color = color; } @Override public String getColor() { return color; } @Override public void disPlsy(Coordinate c) { System.out.println("颜色:"+color); System.out.println("位置:"+c.getX()+","+c.getY()); } } package com.liang.flyWeight; import java.util.HashMap; import java.util.Map; /** * FlyWeightFactory享元工厂 * @author Administrator * */ public class ChessFlyWeightFactory { private static Map<String,ChessFlyWeight> map=new HashMap<>(); public static ChessFlyWeight getChess(String color) { if(map.get(color)!=null) { return map.get(color); }else { ChessFlyWeight chess=new ConcreteChess(color); map.put(color, chess); return chess; } } } public class Client { public static void main(String[] args) { //不同对象 ChessFlyWeight chess1=new ConcreteChess("黑色"); ChessFlyWeight chess2=new ConcreteChess("黑色"); System.out.println(chess1); System.out.println(chess2); chess1.disPlsy(new Coordinate(12, 25)); chess2.disPlsy(new Coordinate(17, 25)); //通过享元工厂生产相同颜色的相同对象 ChessFlyWeight chess3=ChessFlyWeightFactory.getChess("白色"); ChessFlyWeight chess4=ChessFlyWeightFactory.getChess("白色"); System.out.println(chess3); System.out.println(chess4); chess3.disPlsy(new Coordinate(12, 45));//增加外部状态 chess4.disPlsy(new Coordinate(82, 75));//增加外部状态 } }

最新回复(0)