Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the meta-sharing model of Java?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain "what is the meta-model of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the meta-model of Java?"

Preface

Just imagine, if we want to use programs to design go games, with 181sunspots and 180whites, do we have to new a chess sub-object every time we play a piece? Java is an object-oriented language. We all know that if we keep new new objects in memory, when there are too many objects and the collection is not timely, it will lead to high running cost and performance degradation. So how do we solve this kind of problem? Next, we will explain the focus of this article, the Java design pattern-- sharing meta-pattern.

What is the sharing meta-model?

To make it easier to understand, let's take a look at the two states of the meta-sharing mode:

Internal state (Intrinsic State): a state that is stored inside a shared meta-object and does not change with the environment, so it can be shared.

External state (Extrinsic State): a state that changes with the environment and cannot be shared. The external state of the shared meta-object must be saved by the client and passed into the shared meta-object when needed after the sharing meta-object has been created. One external state is independent of another external state.

The sharing meta-mode divides the state of an object into internal state and external state, in which the two are independent of each other, share the same internal state, and change the characteristics of the object by setting different external states. let an object have different characteristics, but the internal state is always shared and unchangeable. That is, changing the external state does not cause a change in the internal state.

We can think of go as a sharing mode, their size, shape and color are the internal state, and the position of the pieces is the external state, so that in the design, only two objects of black and white pieces need to be set, black chess shares the black internal state, white chess shares the white internal state, the position of each piece on the chessboard is their external state, there are 361 intersection positions on the go board, and each piece falls in one position (external state). Will not change the color of the pieces (internal state). Isn't it easier to understand?

The shared meta pattern is generally used in conjunction with the factory pattern in order to create a shared meta factory to maintain the shared meta pool (Flyweight Pool), which stores shared meta objects with the same internal state. In the ever-changing daily business, there are few internal states that can be shared, so shared meta-objects are generally designed as smaller objects and contain few internal states, and such objects also become fine-grained objects.

Now let's take a look at the English definition of the sharing meta-pattern:

Flyweight Pattern: Use sharing to support large numbers of fine-grained objects efficiently.

The use of sharing technology to effectively support the reuse of a large number of fine-grained objects. (Flyweight I do not understand why the domestic translation into Heng Yuan, did not find the information, may be according to the role and characteristics of this model translation, if there are friends who know, please leave a message at the end of the text, thank you! )

Let's take a look at the domestic explanation of the sharing model:

Shared meta-pattern (Flyweight Pattern): using sharing technology to effectively support the reuse of a large number of fine-grained objects. The system only uses a small number of objects, and these objects are very similar, the state change is very small, and the objects can be reused many times. Because the shared meta-pattern requires that the objects that can be shared must be fine-grained objects, it is also called lightweight schema, which is an object structural pattern.

In short: the purpose of sharing meta-pattern is to reduce the number of objects and save memory by sharing immutable parts.

Enjoy the four roles of meta-mode

Flyweight (Abstract share metaclass): interfaces or abstract classes that declare public methods that provide the internal state of the object to the outside world and set the external state.

ConcreteFlyweight (concrete shared metaclass): implements an abstract shared metaclass whose instance is called a shared meta-object. Must be shareable and need to encapsulate the internal state of the shared meta-object.

UnsharedConcreteFlyweight (non-shared concrete sharing meta-class): non-shared shared meta-objects, not all shared meta-objects can be shared, non-shared shared meta-objects are usually composite objects of shared meta-objects.

FlyweightFactory (shared meta-factory class): shared meta-factory, which is mainly used to create and manage shared meta-objects and provide interfaces to access shared meta-objects. It aims at abstract shared meta-class programming, storing various types of concrete shared meta-objects in a shared meta-pool, which is generally designed as a collection of "key-value pairs" (or other types of collections), which can be designed in combination with factory patterns. When a user requests a specific share meta object, the share meta factory provides an instance that has been created in the share meta pool or creates a new instance (if it does not exist), returns the newly created instance and stores it in the share meta pool.

UML diagram of sharing meta-mode

Code example

I will not use the example of me playing chess with Uncle Li, so as not to leave a trauma on his eldest (young) mind. With regard to the case of chess pieces, there are also many versions on the Internet, which you can see for yourself if you are interested. Let's use Arena of Valor's game as an example. We know that in a game against each other, there will be a wave of small soldiers and super soldiers every few minutes. The small soldiers all look exactly the same, and so are the super soldiers. If the Masters team designs a small soldier to come out and new a small soldier object, then in this game in which millions or more people compete online at the same time, the pressure on the server simply cannot stand. Can you score well, fluently and happily? primary school students obediently do their homework at home long after school.

So how to design it? We can take the soldier's physical signs, assembly, and arms as the internal state, and then the direction in which they attack on the map as the external state, so that no matter which direction the soldier attacks (how the external state changes), it will not change the soldier's physical signs and arms (internal state), so that when we develop, as long as each arm has a shared meta-object. Take a look at the code:

1. Write abstract share metaclass

Package com.weiya.mazhichu.designpatterns.flyweight;/** function: abstract share metaclass *

* * @ author Moore * @ ClassName Soldier flyweight. * @ Version V1.0. * @ date 2019.09.03 21:06:52 * / public interface SoldierFlyweight {/ * * function: enemy attack method *

* * @ param direction: * @ author Moore * @ date 2019.09.03 21:06:52 * / public void attack (String direction);}

2. Write specific sharing metaclass

Package com.weiya.mazhichu.designpatterns.flyweight;/** function: specific metaclass *

* * @ author Moore * @ ClassName Concrete solider flyweight. * @ Version V1.0. * @ date 2019.09.04 09:45:41 * / public class ConcreteSoliderFlyweight implements SoldierFlyweight {/ / Internal status private String soliderType; public ConcreteSoliderFlyweight (String soliderType) {this.soliderType = soliderType;} @ Override public void attack (String direction) {if ("normal" .equals (soliderType)) {System.out.println ("ordinary soldiers join the battlefield") } if ("super" .equals (soliderType)) {System.out.println ("Super soldiers join the battlefield");} System.out.println ("attack direction:" + direction);}}

3. Write Hengyuan factory

Package com.weiya.mazhichu.designpatterns.flyweight;import java.util.HashMap;import java.util.Map;/** function: enjoy Yuan Factory *

* * @ author Moore * @ ClassName Soldier fly weight factory. * @ Version V1.0. * @ date 2019.09.03 21:06:58 * / public class SoldierFlyWeightFactory {/ / Factory instance private static SoldierFlyWeightFactory INSTANCE; / / Hang Yuanchi private static Map soldierMap = new HashMap (); private SoldierFlyWeightFactory () {SoldierFlyweight normalSoldier = new ConcreteSoliderFlyweight ("normal"); soldierMap.put ("normal", normalSoldier); SoldierFlyweight superSolider = new ConcreteSoliderFlyweight ("super"); soldierMap.put ("super", superSolider) } / * * function: get factory instance *

* * @ return soldier fly weight factory * @ author Moore * @ date 2019.09.03 21:07:02 * / public static SoldierFlyWeightFactory getInstance () {if (INSTANCE = = null) {INSTANCE = new SoldierFlyWeightFactory (); return INSTANCE;} return INSTANCE;} / * * function: get the shared meta-object *

* * @ param soliderType: * @ return soldier flyweight * @ author Moore * @ date 2019.09.03 21:07:02 * / public SoldierFlyweight getSolider (String soliderType) {return soldierMap.get (soliderType);} / * * function: get the number of objects in Yuanchi *

* * @ return int * @ author Moore * @ date 2019.09.03 21:07:02 * / public int getSoliderSize () {return soldierMap.size ();}}

4. Client test

Package com.weiya.mazhichu.designpatterns.flyweight;/** function: *

* * @ author Moore * @ ClassName Honour of kings test. * @ Version V1.0. * @ date 2019.09.03 21:06:44 * / public class HonourOfKingsTest {public static void main (String [] args) {System.out.println ("the enemy still has five seconds to reach the battlefield!") ; SoldierFlyWeightFactory factory = SoldierFlyWeightFactory.getInstance (); SoldierFlyweight soldier1 = factory.getSolider ("normal"); SoldierFlyweight soldier2 = factory.getSolider ("normal"); SoldierFlyweight soldier3 = factory.getSolider ("normal"); soldier1.attack ("on the road"); soldier2.attack ("middle road"); soldier3.attack ("lower road"); System.out.println (soldier1 = = soldier2) System.out.println (soldier2 = = soldier3); System.out.println ("- -"); System.out.println ("Master has been defeated!"); SoldierFlyweight soldier4 = factory.getSolider ("super"); SoldierFlyweight soldier5 = factory.getSolider ("super"); SoldierFlyweight soldier6 = factory.getSolider ("super") Soldier4.attack ("on the road"); soldier5.attack ("middle road"); soldier6.attack ("down the road"); System.out.println ("remnant blood of the opposing mage, killed by super soldiers."); System.out.println (soldier4 = = soldier5); System.out.println (soldier5 = = soldier6) System.out.println ("- -"); System.out.println ("this case generates a total of objects:" >

View the running results:

It can be seen that we have sent a total of six small soldiers, including three ordinary soldiers and three super soldiers, but there are only two objects (one ordinary soldier and one super soldier) in the sharing pool, that is to say, no matter how many ordinary soldiers or super soldiers are dispatched, no matter which way they attack, it will not affect the internal state of the soldiers, thus greatly reducing the objects of the whole system and reducing memory consumption. If it is not stuck, it will not affect the game experience, and primary school students can come out happily to cheat people, but they should put their studies first.

Enjoy meta-mode extension

In the above example, we are mainly talking about specific shared meta-objects, that is, all shared meta-objects must be shared. But among the four roles of the shared meta-pattern, there is also a non-shared meta-implementation object. What does it mean? as the name implies, the shared meta-object does not have to be shared, but it is usually used as a composite object of the shared meta-object. From this point of view, we divide the sharing meta-object into:

Pure sharing meta-mode: in the pure sharing meta-mode, all shared meta-objects can be shared, that is, all subclasses of abstract shared meta-classes can be shared, and there is no non-shared concrete shared meta-class.

Compound sharing meta-pattern: some simple shared meta-objects can be formed by combining some simple shared meta-objects, which can not be shared by themselves, but they can be decomposed into simple shared meta-objects, while the latter can be shared. (the composite shared meta-object implements the abstract shared meta-class, and its instance is a non-shared shared meta-implementation object.)

In the compound sharing meta-mode, each pure shared meta-object that makes up the composite shared meta-object has its own internal state, and the external state of each simple shared meta-object is the same as that of the compound shared meta-object. Therefore, the compound sharing meta-mode can set the same external state to multiple simple shared meta-objects, which is also the application scene of the compound shared meta-mode.

I will not repeat the simple meta-sharing mode. Let's take a look at the above examples of chess pieces or pesticides. The following is mainly about the combined meta-sharing mode and why it is not shared. Let's take a look at the code:

1. Write compound meta-role classes

Package com.weiya.mazhichu.designpatterns.flyweight;import java.util.HashMap;import java.util.Map;/** function: composite shared meta-role class (non-shared meta-implementation object) *

* * @ author Moore * @ ClassName Concrete composite solider flyweight. * @ Version V1.0. * @ date 2019.09.04 10:56:11 * / public class ConcreteCompositeSoliderFlyweight implements SoldierFlyweight {private static Map soldierMap = new HashMap (); / * * function: add pure meta-objects *

* * @ param soliderType: * @ param flyweight: * @ author Moore * @ date 2019.09.04 10:56:11 * / public void add (String soliderType,SoldierFlyweight flyweight) {soldierMap.put (soliderType,flyweight) } / * * function: flyWeights is a collection of pure sharing meta-objects, which have the same external state extrinsicState. * call the attack method of the pure sharing meta-object using a loop when calling.

* * @ param direction: * @ author Moore * @ date 2019.09.03 21:06:52 * / @ Override public void attack (String direction) {SoldierFlyweight flyweight = null; for (String str: soldierMap.keySet ()) {flyweight = soldierMap.get (str); flyweight.attack (direction);}} / * * remove the simple sharing meta-object. * @ param soliderType * / private void remove (String soliderType) {soldierMap.remove (soliderType);}}

2. The modified meta-factory role class

Package com.weiya.mazhichu.designpatterns.flyweight;import java.util.HashMap;import java.util.List;import java.util.Map;/** function: enjoy Yuan Factory *

* * @ author Moore * @ ClassName Soldier fly weight factory. * @ Version V1.0. * @ date 2019.09.03 21:06:58 * / public class SoldierFlyWeightFactory {/ / Factory instance private static SoldierFlyWeightFactory INSTANCE; / / Hang Yuanchi private static Map soldierMap = new HashMap (); private SoldierFlyWeightFactory () {SoldierFlyweight normalSoldier = new ConcreteSoliderFlyweight ("normal"); soldierMap.put ("normal", normalSoldier); SoldierFlyweight superSolider = new ConcreteSoliderFlyweight ("super"); soldierMap.put ("super", superSolider) } / * * function: get factory instance *

* * @ return soldier fly weight factory * @ author Moore * @ date 2019.09.03 21:07:02 * / public static SoldierFlyWeightFactory getInstance () {if (INSTANCE = = null) {INSTANCE = new SoldierFlyWeightFactory (); return INSTANCE;} return INSTANCE } / * * function: get the sharing meta-object (simple meta-factory method) *

* * @ param soliderType: * @ return soldier flyweight * @ author Moore * @ date 2019.09.03 21:07:02 * / public SoldierFlyweight getSolider (String soliderType) {return soldierMap.get (soliderType);} / * * function: compound sharing meta-factory method *

* * @ param compositeSoliderTypes: * @ return soldier flyweight * @ author Moore * @ date 2019.09.04 11:06:24 * / public SoldierFlyweight getCompositeSolider (List compositeSoliderTypes) {ConcreteCompositeSoliderFlyweight compositeFlyweight = new ConcreteCompositeSoliderFlyweight (); for (String soliderType: compositeSoliderTypes) {compositeFlyweight.add (soliderType,this.getSolider (soliderType));} return compositeFlyweight } / * * function: get the number of objects in the share pool *

* * @ return int * @ author Moore * @ date 2019.09.03 21:07:02 * / public int getSoliderSize () {return soldierMap.size ();}}

3. Write test classes

Package com.weiya.mazhichu.designpatterns.flyweight;import java.util.ArrayList;import java.util.List;/** function: test pure sharing mode and compound sharing mode

* * @ author Moore * @ ClassName Flyweight test. * @ Version V1.0. * @ date 2019.09.04 11:08:51 * / public class FlyweightTest {public static void main (String [] args) {SoldierFlyWeightFactory factory = SoldierFlyWeightFactory.getInstance (); String soliderType = "normal"; SoldierFlyweight soldierFlyweight1 = factory.getSolider (soliderType); SoldierFlyweight soldierFlyweight2 = factory.getSolider (soliderType); soldierFlyweight1.attack ("on the road"); soldierFlyweight2.attack ("middle road") System.out.println ("- -"); List compositeSoliderType = new ArrayList (); compositeSoliderType.add ("normal"); compositeSoliderType.add ("super"); compositeSoliderType.add ("normal"); compositeSoliderType.add ("super"); compositeSoliderType.add ("normal") SoldierFlyweight compositeSoliderFlyeweight1 = factory.getSolider (compositeSoliderType); SoldierFlyweight compositeSoliderFlyeweight2 = factory.getSolider (compositeSoliderType); compositeSoliderFlyeweight1.attack ("on the road"); compositeSoliderFlyeweight2.attack ("middle road"); System.out.println ("- -"); System.out.println ("whether the meta-mode of pure sharing shares objects:" >

View the running results:

Combined with the running results, let's take a look at this paragraph word by word, and you should be able to understand it.

In the compound sharing meta-mode, each pure shared meta-object that makes up the composite shared meta-object has its own internal state, and the external state of each simple shared meta-object is the same as that of the compound shared meta-object. Therefore, the compound sharing meta-mode can set the same external state to multiple simple shared meta-objects, which is also the application scene of the compound shared meta-mode.

Compound shared meta-mode UML diagram

Summary of sharing meta-model

Working with scen

The system has a large number of similar or identical objects. Due to the extensive use of such objects, it consumes a lot of memory.

Scenarios where buffer pools are required (shared meta-pools, that is, when shared meta-objects need to be used multiple times).

Most of the states of an object can be externalized, and these external states can be passed into the object.

Advantages

Greatly reduce the creation of objects, reduce the memory of the system, and improve the efficiency.

The external state of the shared meta-pattern is relatively independent and does not affect its internal state, so that the shared meta-objects can be shared in different environments.

Shortcoming

It is necessary to separate the external state from the internal state, which increases the complexity of the system.

Reading the external state of the shared meta mode makes the run time slightly longer.

At this point, I believe you have a deeper understanding of "what is the meta-mode of Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report