“This is the seventh day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”
First, enjoy the concept of meta patterns and roles
(A), enjoy the concept of yuan model
The enjoy meta pattern, also known as the lightweight pattern, is an implementation of object pooling. Similar to thread pools, thread pools avoid the performance cost of constantly creating and destroying multiple objects. Provides a way to reduce the number of objects to improve the application’s object structure. Its purpose is to share fine-grained objects and centralize multiple access to the same object without having to create a separate object for each visitor, thus reducing memory consumption. It belongs to the structural pattern.
The enjoy element mode divides the state of an object into internal state and external state. The internal state is invariable and the external state is variable. Then the number of objects is reduced and memory is saved by sharing the invariant parts.
The essence of the share element pattern is to cache shared objects, reducing memory consumption.
(2), enjoy the role of the yuan model
Flyweight: A Flyweight object abstracts a base class or interface and defines the interface or implementation of the object’s external state and internal state.
ConcreteFlyweight: A business that implements the abstract role definition. The role’s internal state handling should be environment independent, and there should be no case where an operation changes the internal state while modifying the external state.
FlyweightFactory: Manages the FlyweightFactory pool and creates FlyweightFactory objects.
Ii. Application scenarios of the Enjoy Yuan mode
1, often used in the bottom of the system development, in order to solve the performance of the system.
2. Scenarios where the system has a large number of similar objects and requires buffer pools.
Three, enjoy the meta pattern of code examples
Abstract enjoy element role: Ticket
public interface Ticket {
void showInfo(String bunk);
}
Copy the code
The specific share yuan role is TrainTicket
public class TrainTicket implements Ticket {
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".this.from, this.to, bunk, this.price) ); }}Copy the code
Hengyuan factory: TicketFactory
public class TicketFactory {
private static Map<String, Ticket> ticketPool = new ConcurrentHashMap<String, Ticket>();
public static Ticket queryTicket(String from, String to) {
String key = from + "- >" + to;
if (TicketFactory.ticketPool.containsKey(key)) {
System.out.println("Use cache");
return TicketFactory.ticketPool.get(key);
}
System.out.println("First query, create object:" + key);
Ticket ticket = new TrainTicket(from, to);
TicketFactory.ticketPool.put(key, ticket);
returnticket; }}Copy the code
Four, enjoy the application of meta mode in the source code
(1) Enjoy element mode in String
Test code:
public class Main {
public static void main(String[] args) {
// Both s1 and S2 are assigned constants
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);
// S3 is assigned to a constant, s4 is assigned to a constant plus a variable
String s3 = "he" + "llo";
String s4 = "he" + new String("llo");
System.out.println(s3 == s4);
// S5 is assigned to variables and S6 is assigned to the intern() method
String s5 = new String("hello");
String s6 = s5.intern();
System.out.println(s5 == s6);
// s1 is assigned to constant and S6 is assigned to the intern() methodSystem.out.println(s1 == s6); }}Copy the code
Java defines String classes as final. Strings in the JVM are stored in the constant pool. Java will ensure that there is only one copy of a String in the constant pool. The JVM takes it out of the permanent generation and places it in the heap.
In the above code example, when a String variable is created as a literal because of the final decoration of the String class, the JVM puts that literal into the pool of String constants at compile time. It is loaded into memory when it is started by a Java program. As in the above example, the “hello” assignment for S1 is placed into the constant pool, and the assignment for S6 is assigned through the intern() method. The contents of S5 are “hello”, so the value of S6 is also pointed to the constant pool.
(2) Enjoy element mode of Integer
Test code:
public class Main {
public static void main(String[] args) {
Integer a = Integer.valueOf(100);
Integer b = 100;
Integer c = Integer.valueOf(1000);
Integer d = 1000;
System.out.println("A = = b:" + (a == b));
System.out.println(C = = d: ""+ (c == d)); }}Copy the code
The Integer source code:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Copy the code
By analyzing the source code, we know that the valueOf method in the Integer source code makes a judgment that if the target value is between -128 and 127, the value is directly taken from the cache, otherwise the new object is created. This is where the enjoyment meta-pattern is used. To improve performance.
Five, enjoy the internal state and external state of the yuan mode
The definition of the enjoy meta schema presents two invitations: fine-grained and shared objects. Because of the need for fine-grained objects, there will inevitably be a large number of objects with similar properties. In this case, we divide the information about these objects into two parts: internal state and external state.
Internal state refers to the information shared by an object, stored inside the share element object and does not change with the environment.
An external state is a non-shareable state that changes with the environment upon which an object can depend.
For example, the connection object in the connection pool, the user name, password, and connection URL stored in the connection object are set when the object is created and will not change with the environment. These are internal states. And for every connection that needs to be recycled, we need to mark it as available, and these are the external states.
Six, enjoy yuan model advantages and disadvantages
(I) Advantages
1, reduce the creation of objects, reduce the number of objects in memory, reduce the memory of the system, improve efficiency
2. Reduce the usage of resources other than memory
(ii) Shortcomings
1. Pay attention to the internal and external state; Focus on thread safety
2. To complicate the logic of a system or program