用来尽可能减少内存使用量,适用于存在大量重复对象的场景,达到对象共享,避免创建过多对象的效果,提升性能,避免内存溢出。
定义:
使用共享对象有效支持大量细粒度对象。
适用场景:
- 系统中存在大量相似对象;
- 细粒度对象具备接近外部状态,内部状态与环境无关;
- 需要缓冲池。
亨元模式其实是通过集合来缓冲对象,获取的时候,先判断集合里面是否存在该对象,如果有就取出来,没有创建新的,避免不必要的对象创建。
简单例子:
接口类:
public interface Ticket {public void showTicketInfo(String bunk); }
接口实现类:
public class AirTicket implements Ticket {public String from;public String to;public String bunk;public int price;public AirTicket(String from, String to) {this.from = from;this.to = to;}@Overridepublic void showTicketInfo(String bunk) {price = new Random().nextInt(300);System.out.println("从" + from + "到" + to + "的" + bunk + "价格:" + price);} }
亨元工厂类,创建对象池,创建亨元对象:
public class AirTicketFactory {public static Map<String, Ticket> tickets = new ConcurrentHashMap<String, Ticket>();/*** 亨元模式具体体现,缓冲对象数据,减少对象创建* @param from* @param to* @return*/public static Ticket getTicket(String from, String to) {String key = from + "-" + to;if (tickets.containsKey(key)) {return tickets.get(key);}else {AirTicket airTicket = new AirTicket(from, to);tickets.put(key, airTicket);return airTicket;}} }
测试类:
public class Main {public static void main(String[] args) {Ticket toXianAirTicket0 = AirTicketFactory.getTicket("深圳", "西安");Ticket toBeiJingAirTicket = AirTicketFactory.getTicket("深圳", "北京");Ticket toXianAirTicket1 = AirTicketFactory.getTicket("深圳", "西安");Ticket toXianAirTicket2 = AirTicketFactory.getTicket("深圳", "西安");toXianAirTicket0.showTicketInfo("头等舱");toBeiJingAirTicket.showTicketInfo("商务舱");toXianAirTicket1.showTicketInfo("头等舱");toXianAirTicket2.showTicketInfo("头等舱");} }
结果:
从深圳到西安的头等舱价格:114 从深圳到北京的商务舱价格:215 从深圳到西安的头等舱价格:231 从深圳到西安的头等舱价格:103