concept

This method is applicable to scenarios where there may be a large number of duplicate objects. Objects can be shared by caching to avoid creating too many objects. The fields in the share object can be divided into the following parts: internal state (does not change with the environment, can be shared); External state (varies with environment and is not shareable). Generally, in the share mode, an object container Map is established, namely, the share object factory. The internal state is the key and the value is the share object itself. The client obtains the share object from the share object factory. Complex system, but efficient memory optimization.

Application scenarios

String constant pools, database connection pools, buffer pools, and so on are all examples of meta-schema applications

implementation

Take selling train tickets for example, train tickets are the object of the yuan, the internal state is from a fixed time to a fixed time.

public interface Ticket { public void showTicketInfo(String bunk); } public Ticket Ticket implements Ticket {public String from; public String to; public String bunk; public int price; TrainTicket (String from, String to){ this.from = from; this.to = to; } @Override public void showTicketInfo(String bunk){ System.out.println(100); } } public class TicketFactory { static Map<>String ,Ticket> map = new ConcurrentHashMap(); public static Ticket getTicket(String from, String to){ String key = from +"-" + to;
        if(map.containsKey(key)){
            return map.get(key);
        } else {
            Ticket t = new TrainTicket(from,to);
            map.put(key,t);
            returnt; }}}Copy the code