设计模式之 享元模式
享元模式 通过对象的复用来减少对象创建的次数和数量,以减少系统内存的使用和降低系统的负载。在系统需要一个对象时,享元模式首先在系统中查找并尝试重用现有的对象,如果未找到匹配的对象,则创建新对象并将其缓存在系统中以便下次使用。
(1)定义Memory
public class Memory{ private int size; private boolean isused; private String id; public Memory(int size,boolean isused,String id){ this.size = size; this.isused = isused; this.id = id; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public boolean isIsused() { return isused; } public void setIsused(boolean isused) { this.isused = isused; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
(2)定义MemoryFactory工厂
public class MemoryFactory{ private final static Log logger = LogFactory.getLog(this.getClass()); private static List<Memory> memoryList = new ArrayList<>(); public static Memory getMemory(int size){ Memory memory = null; for (int i = 0; i<memoryList.size();i++){ memory = memoryList.get(i); // 如果存在和需求size一样大小并且未使用的内存块,则直接使用 if (memory.getSize() == size && memory.isIsused() == false){ memory.setIsused(true); memoryList.set(i,memory); logger.info("get memory from memoryList"); break; } } if (memory == null){ memory = new Memory(32,false, UUID.randomUUID().toString()); memoryList.add(memory); } return memory; } // 释放内存 public static void releaseMemory(String id){ for (int i = 0; i < memoryList.size(); i++) { Memory memory = memoryList.get(i); if (memory.getId().equals(id)){ memory.setIsused(false); memoryList.set(i,memory); logger.info("release memory"+id); break; } } } }
(3)使用享元模式
public static void main(String[] args){ // 获取内存 Memory memory = MemoryFactory.getMemory(32); // 释放内存 MemoryFactory.releaseMemory(memory.getId()); // 重新获取内存 MemoryFactory.getMemory(32); }