Fork me on GitHub

轻量级的对象池-享元模式

享元模式又称Flyweight,代表轻量级的意思,适用于可能存在大量可重复对象的场景

这里举一个售卖火车票的例子

共享对象的接口,这里是火车票接口

1
2
3
public interface Ticket {
void showTicketInfo(String bunk);
}

具体对象类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class TrainTicket implements Ticket {
public String from;
public String to;
public String bunk;
public int price;
public TrainTicket(String from, String to) {
this.from = from;
this.to = to;
price = new Random().nextInt(300);
}
@Override
public void showTicketInfo(String bunk) {
System.out.println(from + "到" + to + "的" + bunk +"火车票价格:" + price);
}
}

对象生产工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
public class TickFactory {
static Map<String, Ticket> stringTicketMap = new ConcurrentHashMap<>();
public static Ticket getTicket(String from, String to) {
String key = from + "-" + to;
if (stringTicketMap.containsKey(key)) {
return stringTicketMap.get(key);
} else {
Ticket ticket =new TrainTicket(from, to);
stringTicketMap.put(from + "-" + to,ticket);
return ticket;
}
}
}

在这里我们使用了一个map来存放已经存在的对象,这也是享元模式的关键,这样就不用每次都重新创建对象,减少内存的消耗

使用如下

1
2
3
4
5
6
7
8
9
10
public class Main {
public static void main(String[] args) {
Ticket ticket = TickFactory.getTicket("长兴", "武汉");
ticket.showTicketInfo("上铺");
Ticket ticket1 = TickFactory.getTicket("武汉", "长兴");
ticket1.showTicketInfo("软卧");
Ticket ticket2 = TickFactory.getTicket("长兴", "武汉");
ticket2.showTicketInfo("上铺");
}
}

结果

1.PNG