介绍
享元模式主要用于减少创建对象的数量,以减少内存占用和提高性能。
使用场景:
1.系统存在大量相似对象。
2.需要对象缓冲池的场景。
优点:
减少对象的创建,降低系统的内存使效率提高,避免了频繁GC。
缺点:
提高了系统的复杂度,需要分离出外部状态和内部状态,外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。
UML类图
外部状态:此例中是from, to, type。
内部状态:此例中是随机生成价格。
代码实现
Ticket.java
public interface Ticket {
public void showTicketInfo();
}
TrainTicket.java
public class TrainTicket implements Ticket {
public String from;
public String to;
public String type;
public int price;
public TrainTicket(String from, String to, String type) {
this.from = from;
this.to = to;
this.type = type;
}
@Override
public void showTicketInfo() {
price = new Random().nextInt(500);
System.out.println("The ticket " + from + " to " + to + " of " + type + " is ¥" + price);
}
}
TicketCenter.java
public class TicketCenter {
static Map<String, Ticket> ticketMap = new ConcurrentHashMap<>();
public static Ticket getTicket(String from, String to, String type) {
String key = from + "-" + to + "-" + type;
if (ticketMap.containsKey(key)) {
System.out.println("Use Cache Ticket ==> " + key);
return ticketMap.get(key);
} else {
System.out.println("Create New Ticket ==> " + key);
Ticket ticket = new TrainTicket(from, to, type);
ticketMap.put(key, ticket);
return ticket;
}
}
}
Main.java
public class Main {
public static void main(String[] args) {
TicketCenter.getTicket("青岛", "北京", "硬座").showTicketInfo();
TicketCenter.getTicket("青岛", "北京", "硬座").showTicketInfo();
TicketCenter.getTicket("青岛", "北京", "软卧").showTicketInfo();
TicketCenter.getTicket("青岛", "烟台", "硬卧").showTicketInfo();
}
}
输出
Create New Ticket ==> 青岛-北京-硬座
The ticket 青岛 to 北京 of 硬座 is 304
Use Cache Ticket ==> 青岛-北京-硬座
The ticket 青岛 to 北京 of 硬座 is 184
Create New Ticket ==> 青岛-北京-软卧
The ticket 青岛 to 北京 of 软卧 is 485
Create New Ticket ==> 青岛-烟台-硬卧
The ticket 青岛 to 烟台 of 硬卧 is 432