(2)需要缓冲池的场景
public interface Ticket {
public void showTicketInfo(String info);
}
public class TrainTicket implements Ticket {
private String from;
private String to;
//构造函数
public TrainTicket(String from,String to){
this.from =from;
this.to = to;
}
@Override
public void showTicketInfo(String info) {
int price = new Random().nextInt(200);
Log.d("Ticket",from+"-"+to+":"+price+"元");
}
}
public class TicketFactory {
private static Map<String,Ticket> sTicketFactory = new ConcurrentHashMap<>();
public static Ticket getTicketFromFactory(String from,String to){
String key = from+"-"+to;
if (sTicketFactory.containsKey(key)){
Log.d("Ticket","从缓存中读取");
return sTicketFactory.get(key);
}else {
Ticket ticket = new TrainTicket(from,to);
sTicketFactory.put(key,ticket);
Log.d("Ticket", "新创建一个对象");
return ticket;
}
}
}
TicketFactory.getTicketFromFactory("海南","上海").showTicketInfo("特等座");
TicketFactory.getTicketFromFactory("海南","上海").showTicketInfo("二等座");
TicketFactory.getTicketFromFactory("海南","上海").showTicketInfo("硬座");
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}