个人博客
http://www.milovetingting.cn
享元模式
模式介绍
享元模式是对象池的一种实现,用来尽可能减少内存使用量,它适合用于可能存在大量重复对象的场景,来缓存可共享的对象,达到对象共享、避免创建过多对象的效果,以提升性能、避免内存移除等。
模式定义
使用共享对象可有效地支持大量的细粒度的对象。
使用场景
- 系统中存在大量的相似对象 
- 细粒度的对象都具备较接近的外部状态,而且内部状态与环境无关,也就是说对象没有特定身份 
- 需要缓冲池的场景 
简单使用
创建接口
| 12
 3
 4
 5
 
 | public interface Ticket {
 public void showTicketInfo(String bunk);
 
 }
 
 | 
实现接口
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | public class TrainTicket implements Ticket {
 private String from;
 private String to;
 private int price;
 
 public TrainTicket(String from, String to) {
 super();
 this.from = from;
 this.to = to;
 }
 
 @Override
 public void showTicketInfo(String bunk) {
 price = new Random().nextInt(300);
 System.out.println("购买 从 " + from + " 到 " + to + " 的 " + bunk + " 火车票,价格:" + price);
 }
 
 }
 
 | 
创建工厂类
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | public class TicketFactory {
 static Map<String, Ticket> sTicketMap = new ConcurrentHashMap<String, Ticket>();
 
 public static Ticket getTicket(String from, String to) {
 String key = from + "-" + to;
 if (sTicketMap.containsKey(key)) {
 System.out.println("使用缓存==>" + key);
 return sTicketMap.get(key);
 } else {
 System.out.println("创建对象==>" + key);
 Ticket ticket = new TrainTicket(from, to);
 sTicketMap.put(key, ticket);
 return ticket;
 }
 }
 
 }
 
 | 
调用
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | public class Main {
 public static void main(String[] args) {
 Ticket ticket1 = TicketFactory.getTicket("北京", "上海");
 ticket1.showTicketInfo("上铺");
 Ticket ticket2 = TicketFactory.getTicket("北京", "上海");
 ticket1.showTicketInfo("中铺");
 Ticket ticket3 = TicketFactory.getTicket("北京", "上海");
 ticket1.showTicketInfo("下铺");
 }
 
 }
 
 | 
输出结果
| 12
 3
 4
 5
 6
 
 | 创建对象==>北京-上海购买 从 北京 到 上海 的 上铺 火车票,价格:44
 使用缓存==>北京-上海
 购买 从 北京 到 上海 的 中铺 火车票,价格:66
 使用缓存==>北京-上海
 购买 从 北京 到 上海 的 下铺 火车票,价格:86
 
 |