import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* 享元模式: 面向对象技术可以很好的解决一些灵活性或可扩展性问题, 但是在很多情况下需要在系统中增加类和对象的个数, 但是当这些完全一样的对象数量太多的时候, 会导致运行的代价过高, 带来性能下降等问题.
* 享元模式正是为了该问题而诞生.
* 享元模式是对象池的一种实现, 类似于线程池, 数据库连接池, 他们都可以避免不停的创建和销毁带来的高额代价. 享元模式是为了减少内存使用, 避免出现大量重复的创建和销毁对象的场景.
* 享元模式的总是是共享细粒度独享, 将多个同一对象的访问集中起来, 不必为每个访问者创建一个单独的对象, 以此降低内存消耗.
*/
class Client {
public static void main(String[] args) {
ITicket ticket = TicketFactory.queryTicket("深圳北", "潮汕");
ticket.showInfo("硬座");
ticket = TicketFactory.queryTicket("深圳北", "潮汕");
ticket.showInfo("软座");
ticket = TicketFactory.queryTicket("深圳北", "潮汕");
ticket.showInfo("硬卧");
}
interface ITicket {
void showInfo(String bunk);
}
static class TrainTicket implements ITicket {
private String from;
private String to;
private int price;
public TrainTicket(String from, String to) {
this.from = from;
this.to = to;
}
@Override
public void showInfo(String bunk) {
this.price = new Random().nextInt(500);
System.out.println(String.format("%s->%s:%s价格:%s 元", this.from, this.to, bunk, this.price));
}
}
static class TicketFactory {
private static Map<String, ITicket> sTicketPool = new ConcurrentHashMap<>();
public static ITicket queryTicket(String from, String to) {
String key = from + "->" + to;
if (TicketFactory.sTicketPool.containsKey(key)) {
System.out.println("使用缓存 ==> " + key);
return TicketFactory.sTicketPool.get(key);
}
System.out.println("第一次查询,创建对象 ==> " + key);
ITicket ticket = new TrainTicket(from, to);
TicketFactory.sTicketPool.put(key, ticket);
return ticket;
}
}
}