当前位置:网站首页>When I was in the library, I thought of the yuan sharing mode
When I was in the library, I thought of the yuan sharing mode
2022-06-26 16:57:00 【Tianweichang】
Official account “Java Back end technology stack ”
reply “000” Get the necessary e-books for programmers
Hello everyone , I'm Lao Tian , Today I'd like to share with you The flyweight pattern . With the right life story , And design patterns in real project scenarios , Finally, I want to summarize this design pattern with one sentence .
in addition , There is a Saturday prize at the end of the article , Book delivery activities , If you don't participate, you can participate .
The following is the contents of this article :

About Design Patterns Series , We have already shared :
The romance of The Three Kingdoms : The chain of responsibility model
Han Xin pays homage to the general : Delegation mode
3 Necessary for annual work Decorator mode
I have been working for five years , I still don't understand Facade mode
Take out , It reminds me The strategy pattern
Basic essential : Singleton mode 7 A question
Fast grasp Template method Pattern
Five minutes master Archetypal model
background
The flyweight pattern (Flyweight Pattern) It's also called lightweight mode , Is an implementation of the object pool .
It's like a thread pool , Thread pool can avoid creating and destroying multiple objects continuously , Consumption performance .
The flyweight pattern Provides Reduce the number of objects So as to improve the way of applying the required object structure .
English explanation :
Use sharing to support large numbers of fine-grained objects efficiently.
The flyweight pattern (Flyweight Pattern) The aim is Share fine-grained objects , Gather multiple accesses to the same object , You don't have to create a separate object for each visitor , Mainly used to reduce the number of objects created , To reduce memory usage and improve performance .
It's a structural design pattern , Among them, the structural design patterns are as follows : agent 、 The facade 、 Decorator 、 Enjoying yuan 、 The bridge 、 Adapter 、 Combine .
Be careful :
The sharing pattern divides the state of an object into internal state and external state , The internal state is constant , The external state is changing ; And then by sharing the unchanging parts , Reduce the number of objects and save memory .
Life cases
letting agent
As long as it's a city , Housing agents are indispensable , Housing agents have a large amount of information about rental housing , And a housing agency often has multiple stores , But all the stores share this housing information ( What's shared is information about rental housing ).
Personal ID card information
Every Chinese citizen has an ID card , And this ID card information is shared in the public security system , Police stations of public security bureaus all over the country will share your ID card information ( What's shared is personal identity information ).
Fill in the college entrance examination
Every university has a definite quota in every province , These places are shared by all college entrance examination students in the province ( What's shared is the number of places ).
The library
The loanable books in the library , It's shared with many readers , You can check whether the book has been lent out , There's still a lot left to borrow ( Shared books ).
....
Simple code implementation
Let's demonstrate the Heyuan mode through a case ( Take the library as an example ).
public interface Book {
void borrow();
}
/**
* @author java Back end technology stack
*/
public class ConcreteBook implements Book {
// The title of the book being lent out
private String name;
public ConcreteBook(String name) {
this.name = name;
}
@Override
public void borrow() {
System.out.println(" The library lent out a Book , Title :"+this.name);
}
}
import java.util.HashMap;
import java.util.Map;
/** The library
* @author java Back end technology stack
*/
public class Llibrary {
private Map<String, Book> bookMap = new HashMap<>();
private Llibrary() {
}
// There can only be one library
public static Llibrary getInstance() {
return LazyHolder.LAZY_STATIC_SINGLETON;
}
// Through the title of the book name Come and borrow books
public Book libToBorrow(String name) {
Book book;
// If the library has , Just borrow the book
if (bookMap.containsKey(name)) {
book = bookMap.get(name);
} else {// The library doesn't have , Enter a Book , Then borrow the book
book = new ConcreteBook(name);
bookMap.put(name, book);
}
return book;
}
// Back to how many books there are
public int bookSize() {
return bookMap.size();
}
private static class LazyHolder {
private static final Llibrary LAZY_STATIC_SINGLETON = new Llibrary();
}
}
import java.util.ArrayList;
import java.util.List;
public class Student {
private static List<Book> bookList = new ArrayList<>();
private static BookFactory bookFactory;
public static void main(String[] args) {
bookFactory = BookFactory.getInstance();
studenBorrow("java From entry to mastery ");
studenBorrow("java From entry to abandonment ");
studenBorrow("JVM java virtual machine ");
studenBorrow("java Programming idea ");
// After returning it , Borrow it again
studenBorrow("java From entry to mastery ");
studenBorrow("java From entry to abandonment ");
studenBorrow("JVM java virtual machine ");
studenBorrow("java Programming idea ");
// After returning it , Borrow it again
studenBorrow("java From entry to mastery ");
studenBorrow("java From entry to abandonment ");
studenBorrow("JVM java virtual machine ");
studenBorrow("java Programming idea ");
// Lend out every book
for (Book book:bookList){
book.borrow();
}
System.out.println(" The students borrowed "+bookList.size()+" This book ");
System.out.println(" The students borrowed "+ bookFactory.bookSize()+" This book ");
}
private static void studenBorrow(String name) {
bookList.add(bookFactory.libToBorrow(name));
}
}
Running results
The library lent out a Book , Title :java From entry to mastery
The library lent out a Book , Title :java From entry to abandonment
The library lent out a Book , Title :JVM java virtual machine
The library lent out a Book , Title :java Programming idea
The library lent out a Book , Title :java From entry to mastery
The library lent out a Book , Title :java From entry to abandonment
The library lent out a Book , Title :JVM java virtual machine
The library lent out a Book , Title :java Programming idea
The library lent out a Book , Title :java From entry to mastery
The library lent out a Book , Title :java From entry to abandonment
The library lent out a Book , Title :JVM java virtual machine
The library lent out a Book , Title :java Programming idea
The students borrowed 12 This book
The students borrowed 4 This book
Actually , There are only four books in the library , But many people borrow ,A I've finished reading ,B Borrow it again ,B Return it. C Borrow it again .
These books are shared by everyone .
Enjoy yuan mode UML The class diagram is as follows :
As can be seen from the picture above , The sharing pattern mainly includes 3 A character .
Abstract meta roles (
Book): The primitive object abstract base class or interface , An interface or implementation that defines both the external and internal state of an object .Specific enjoy yuan role (
ConcreteBook): Implement the business of abstract role definition . The internal state handling of the role should be environment independent , There will not be an operation to change the internal state 、 At the same time, the external state is modified .The flyweight factory (
BookFactory): Responsible for managing the pool of shareware objects and creating shareware objects .
Maybe you don't quite understand this example , Let's use the common scenes in our work to explain .
How big guys use it
About the Heyuan model , stay JDK A lot of use in , such as :String、Integer、Long And so on , All of them use .
Integer Sharing mode in
What does the following code output ?
/**
* Welcome to the official account :java Back end technology stack
*
* @author Tian Weichang
* @date 2021/06/02 19:30
*/
public class IntegerDemo {
public static void main(String[] args) {
Integer a = 100;
Integer b = Integer.valueOf(100);
System.out.println(a == b);
Integer c = new Integer(1000);
Integer d = Integer.valueOf(1000);
System.out.println(c == d);
}
}
A lot of people might think that output
true
true
Actually , no , The final output here is :
true
false
Why? ?100 You can compare ,1000 You can't compare ?
Actually , stay Integer In this paper, we use the Heyuan mode , It's about putting -128 To 127 This range of data is cached ( Put it in Integer In an array of types ).
static final int low = -128;
public static Integer valueOf(int i) {
//high The default is 127
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Here is a brief analysis :

About Integer The cache of , Recommend reading this article :
here Integer Inside IntegerCache It is used in The flyweight pattern .
About Integer recommend : interviewer : say something Integer Cache range
String Sharing mode in
Java Medium lecture String Class is defined as final Cannot inherit , And set the properties value Also defined as final It's immutable ,JVM In general, the string is stored in the string constant pool ,Java Will ensure that there is only one copy of a string in the constant pool , This string constant pool is in JDK1.6 In the method area ( Forever ) in , and JDK1.7 in the future ,JVM It moved from the method area to the heap heap in .
What does the following code output ?
/**
* Welcome to the official account :java Back end technology stack
*
* @author Tian Weichang
* @date 2021/06/03
*/
public class StringDemo {
public static void main(String[] args) throws Exception {
String s1 = "abcd";
String s2 = "abcd";
String s3 = "ab" + "cd";
String s4 = "ab" + new String("cd");
String s5 = new String("abcd");
String s6 = s5.intern();
String s7 = "a";
String s8 = "bcd";
String s9 = s7 + s8;
System.out.println("s1 == s2 " + (s1 == s2));
System.out.println("s1 == s3 " + (s1 == s3));
System.out.println("s1 == s4 " + (s1 == s4));
System.out.println("s1 == s6 " + (s1 == s6));
System.out.println("s1 == s9 " + (s1 == s9));
System.out.println("s4 == s5 " + (s4 == s5));
}
}
String Class value yes final Embellished , Create in literal form String variable ,JVM This literal will be used during compilation “abcd” Put it in the string constant pool , Yes Java The program is loaded into memory when it starts . The characteristic of this string constant is that it has and only has one copy of the same literal quantity , If other words have the same literal amount ,JVM The reference to this literal is returned , Without the same literal amount , Then create the literal quantity in the string constant pool and return its reference .
because s2 Point to the literal quantity "abcd" It already exists in the constant pool (s1 Precede s2), therefore JVM Returns the literal bound reference , therefore s1==s2.
s3 The combination of Chinese literal quantity is actually JVM Layers have been optimized , stay JVM It's right during compilation s3 Optimized the splicing of , therefore s1、s2、s3 Can be understood as the same , namely s1==s3.
s4 Medium new String("cd"), Two objects are generated ,"cd" and new String("cd"),"cd" Exists in the string constant pool ,new String("cd") It's in the pile heap in ,String s4="ab"+ new String("cd"); It's essentially the addition of two objects , The compiler doesn't optimize it , The result of the addition is in the heap heap in , and s2 Exists in the string constant pool , Of course not , namely s1!=s4.
s4 and s5 The end result is in the heap , So at this time s4!=s5
s5.intern() The method can be a dimension pair. The total string is dynamically added to the string constant pool during runtime ( The content of the string constant pool is that it is loaded when the program is started , If the literal amount of the object exists in the string constant pool , The reference of the literal in the string constant pool is returned , otherwise , Create and copy a copy of the literal quantity to the string constant pool, and then it will be referenced ), therefore s1==s6.
s9 yes s7 and s8 Splicing into , however jvm It's not optimized , therefore s1!=s9
Last , The above code output :
s1 == s2 true
s1 == s3 true
s1 == s4 false
s1 == s6 true
s1 == s9 false
s4 == s5 false
JVM The constant pool in is also one of the classic implementations of the meta sharing pattern .
About String Extend the content :
Interview questions of meituan :String s = new String("111") Several objects will be created ?
Long Sharing mode in
Long neutralization Integer It's similar to , It's also the most -128 To 127 Is cached , Please have a look at Long Medium valueOf() Method source part :
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
There's no need to demonstrate this , and Integer equally , It's all caching , That is to say, Xiangyuan mode .
stay Apache Commons Pool Sharing mode in
The basic idea of object pooling is : Save used objects , The next time you need this object , Take it out and reuse it , So as to reduce the consumption caused by frequent object creation to a certain extent . Used as a storage object “ Containers ” The object of , It's called the object pool (Object Pool, abbreviation Pool).
Apache Pool The function of object pool is realized , Defines the generation of objects 、 The destruction 、 Activate 、 Passivation and its state transition , It also provides several default object pool implementations ,
There are several important roles :
Pooled Object( Pool objects ): Used to encapsulate objects ( for example , Threads 、 Database connection and TCP Connect ), Wrap it up as an object that can be managed by the object pool .
Pooled Object Factory( Pooling object factories ): Defined operations Pooled Object Some methods of instance life cycle ,Pooled Object Factory Must be thread safe .
Object Pool( Object pool ):Object Pool Responsible for managing the Pooled Object, for example , Lending to 、 Returns the object 、 Check object 、 How many active objects and how many free objects .
stay ObjectPool Subclasses of classes org.apache.commons.pool2.impl.GenericObjectPool Species have an attribute :
private final Map<IdentityWrapper<T>, PooledObject<T>> allObjects;
This Map Is used to cache objects , So this is also the implementation of the sharing mode .
An extension of the enjoy mode
Status in the sharing mode
The definition of Heyuan mode puts forward two requirements : fine-grained and Shared objects .
Because fine granularity is required , Therefore, it is inevitable that the number of objects will be large and similar , At this point, we divide the information of these objects into two parts : Internal state and external state .
Internal state Refers to the information shared by objects , It's stored inside the share object , And it doesn't change with the environment ;
External state A token on which an object can depend , Change with the environment , It can't be shared .
such as : Connection objects in the connection pool , The user name saved in the connection object 、 password 、 Connect URL Etc , It's set when you create the object , It doesn't change with the environment , These are internal states . And when every connection is going to be recycled , We need to mark it as available , These are external states .
Advantages and disadvantages
advantage
Reduce the creation of objects , Reduce the number of objects in memory , Reduce system memory , Increase of efficiency .
Reduce the use of resources other than memory .
shortcoming
In focus 、 External state , Pay attention to thread safety .
Make the system 、 The logic of the program is complicated .
summary
The flyweight pattern , In terms of concept alone, it is estimated that many people do not quite understand , But from Integer、String It has been combined with the scenes of life to understand , You can easily understand the Heyuan model , The implementation of the Heyuan pattern is basically accompanied by a collection to store these objects .
One sentence summary :
Optimize resource allocation , Reduce waste of resources
Reference resources :Tom The design pattern course of
Okay , That's the end of today's sharing , I hope you can understand what is the sharing mode , Whether we can learn from the idea of "sharing the yuan mode" in development , Don't say you can't design patterns during the interview .
If there is technical discussion 、 Learning resources are needed , Please add me wechat .

in addition , This Saturday's award is still in full swing , Enter the following official account to reply College entrance examination , To participate
The prize is as follows

Recommended reading
边栏推荐
- Summary of all knowledge points of C language
- proxy
- Interpretation of new plug-ins | how to enhance authentication capability with forward auth
- Count the number of each vowel letter in the string
- Knowing these commands allows you to master shell's own tools
- Fgetc() reads content from file
- The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance
- Qt 5.9.8 安装教程
- Toupper function
- C language -- legal identifier and integer
猜你喜欢

探讨:下一代稳定币

Teach you to learn dapr - 9 Observability

r329(MAIX-II-A(M2A)资料汇总

20: Chapter 3: develop the pass service: 3: get through the redis server in the program; (it only connects with the redis server and does not involve specific business development)

Memory partition model

20:第三章:开发通行证服务:3:在程序中,打通redis服务器;(仅仅是打通redis服务器,不涉及具体的业务开发)

Deployment and operation of mongodb partitioned cluster

Research on natural transition dubbing processing scheme based on MATLAB

Qt 5.9.8 安装教程

No manual prior is required! HKU & Tongji & lunarai & Kuangshi proposed self supervised visual representation learning based on semantic grouping, which significantly improved the tasks of target dete
随机推荐
Sandboxed container: container or virtual machine
Some explanations for latex CJK
[从零开始学习FPGA编程-46]:视野篇 - 集成电路的发展与技术进步
MS | Xie Liwei group found that mixed probiotics and their metabolites could alleviate colitis
I regard it as a dry product with a monthly income of more than 30000 yuan for sidelines and more than 10000 yuan for novices!
Knowing these commands allows you to master shell's own tools
Develop operator based on kubebuilder (for getting started)
Notes on key review of software engineering at the end of the term
Science | 红树林中发现的巨型细菌挑战传统无核膜观念
R329 (maix-ii-a (M2A) data summary
Can Luo Yonghao succeed in entering the AR field this time?
Junit单元测试
C语言 头哥习题答案截图
The texstudio official website cannot be opened
C语言所有知识点小结
Find out the maximum value of each column element of NxN matrix and store it in the one-dimensional array indicated by formal parameter B in order
Day10 daily 3 questions (2): count the number of the largest groups
The student record consists of student number and academic performance. The data of n students have been stored in the a structure array to find out the student record with the lowest performance
Teach you to learn dapr - 2 Must know concept
108. simple chat room 11: realize client group chat