享元模式 是對對象池的一種實現。使用共享對象可以有效地支持大量的細粒度的對象。當系統中存在大量的相似對象,可以使用享元模式;細粒度對象都具備較接近的外部狀態,而且內部狀態與環境無關,也就是說對象沒有特定身份;需要緩衝池的場景,也適合使用享元模式。
1 創建一個接口:
package flyweightpattern2;
public interface Ticket {
public void showTicketInfo(String bunk);
}
2 創建接口的實現類:
package flyweightpattern2;
import java.util.Random;
public class TrainTicket implements Ticket{
public String from;
public String to;
public String bunk;
public 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);
}
}
3 創建管理對象的對象池
package flyweightpattern2;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class TicketFactory {
static Map<String , Ticket> sTicketMap = new ConcurrentHashMap<>();
public static Ticket getTcket(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 new TrainTicket(from, to);
}
}
}
4 測試對象的調用情況:
package flyweightpattern2;
public class Test {
public static void main(String[] args) {
Ticket ticket = TicketFactory.getTcket("A", "B");
ticket.showTicketInfo("上鋪");
Ticket ticket1 = TicketFactory.getTcket("A", "B");
ticket.showTicketInfo("上鋪");
}
}
輸出結果,顯示使用了緩存的對象:
創建對象=A-B
車票:A到B的上鋪---價格:246
使用緩存=A-B
車票:A到B的上鋪---價格:152