In-depth shallow enjoys

xiaoxiao2021-03-06  45

First, the primer

Let us first review the characteristics of the String type in Java: String type object is not changed once it is created; when the contents of the two String objects are the same, JVM only creates a String object to correspond to these two different objects Quote. Let us have confirmed two features (if you already know, skip the second part directly).

First, the second feature is first verified:

Public class testpattern {

Public static void main (String [] args) {

String n = "i love java";

String m = "i love java";

System.out.println (n == m);

}

}

This code will tell you n == m is True, which means that both N and M in JVM references the same String object (if you still can't divide the difference between == and Equals, please confirm) .

So then the first characteristic is verified:

Add a line of code "M = M " Hehe "before the system output"; "At this time, N == M results are false, why is it two ordered to be the same object, isn't it now? The reason is to add a statement after execution, M points to a newly created String object, not the object to modify the reference.

Oh, I said that I almost ran questions, not every String characteristic is related to our theme today. String type design avoids unnecessary resource loss generated when creating N multi String objects, can be said to be an example of enjoying a yuan mode application, then let us start with a little blurred understanding of enjoyment, come and see How to use the correct use of your own programs!

Note: Please follow the suggestions in "Effective Java" using the String type.

Second, definition and classification

Enjoy the "Flyweight Pattern", I am very grateful to the "FlyWeight Pattern translating the strong man who enjoys the yuan mode, because this word understands this mode in the way; if translated into a feather level mode or Fly level mode, etc., although the purpose of using this mode can be improved, but it still does not grab the key to this mode.

The definition of the enjoys mode is: use a shared to avoid a large number of overheads with the same content object. The most common and intuitive in this overhead is the loss of memory. Enjoying Yuan mode is efficiently supported by sharing to support a large number of fine granular objects.

In the name and definition, it reflects the core concept of sharing, so how can you realize your sharing? To know that every thing is different, but there is a certain commonality. If you only share the same thing, you can say that you can say that it is not feasible; so we should try to share the commonality of things, and retain Its personality. In order to do this, the enumeration state and the external state are distinguished in the enjoys. The intrinsic state is common, and the external state is personalized.

Note: The shared object must be unstrenomed, otherwise it changed to change (except for this requirement). The intrinsic state is stored inside the enjoys, which will not be different from the environment. It can be shared; the external state is not shared, which changes with the environment, so the sub-state is customer Keeping (because the environment changes) are caused by the client). In each specific environment, the client passes the external state to the enjoys, thereby creating different objects. As for how to maintain the external state of the client, you don't have to worry about this problem, you don't have to worry about this problem, we will be involved. We reference the classification in Java and Mode, divide the enjoys mode: simple enjoys, composite enjoys. In the next section we will explain the two enjoys.

Third, structure

First, look at the structure of a simple enjoys.

1) Abstract Enjoyment Role: The method that must be implemented is specified for the specific enjoys role, and the external state is incorporated in the form of parameters. In Java, you can be taken by an abstraction class and interface.

2) Specific Enjoyment Role: Implementation of the method specified in the abstract role. If there is an intrinsic state, it is responsible for providing storage space for the intrinsic state.

3) Enjoying Yuan Factory Role: Responsible for creating and managing the enjoys role. To achieve the purpose of sharing, this role is the key!

4) Client role: Maintain reference to all enjoys objects, but also need to store the corresponding hollow state.

To use class diagrams to represent their relationship (see you can see the blog of class diagrams) for class diagrams.

How to see what it is like a simple factory model! That's right, it can be said that the structural simple enjoys mode and the creation of simple factory model are very similar, but its focus or useful but the factory model is very different. The use of factory model is mainly to make the system do not rely on achieving details (see "in-depth light-out factory mode"); while the main purpose of the enjoys, as described earlier: shared techniques are used to avoid a large number of overhead of the same content object. The so-called "old bottle new wine" A!

Let's take a look at the structure of the composite enjoys.

1) Abstract Enjoyment Role: The method that must be implemented is specified for the specific enjoys role, and the external state is incorporated in the form of parameters. In Java, you can be taken by an abstraction class and interface.

2) Specific Enjoyment Role: Implementation of the method specified in the abstract role. If there is an intrinsic state, it is responsible for providing storage space for the intrinsic state.

3) Composite Enjoyment Role: The object it represent is not shared, and can be broken down into a combination of multiple simple enjoys.

4) Enjoying Yuan Factory Roles: Responsible for creating and managing the enjoys role. To achieve the purpose of sharing, this role is the key!

5) Client role: Maintain reference to all enjoys objects, but also need to store the corresponding hollow state.

Currently a simple enjoys, the composite enchanting is more than a composite enchanting role, but its structure has changed a lot. We still use class diagrams:

You may be wondering again, this is like a meeting! Look at the left half, and the simple factory model is similar; look at the right half, how is it like synthetic model (see the article about synthetic model or expecting my "deep shallow synthetic model")! The synthesis mode is used herein to treat the specific enjoys role and composite enjoys role, and can ensure that each simple enjoys included in the composite enjoys in the composite enjoys. Has the same amount, and these simple enumeration states of these simple elements are often different.

Fourth, an example

Here, you will have a detailed description of the way to use the way. The process of going to the vegetation to eliminate the course of eating, everyone must be a light car, here is not described here. In the example I use a list to store the corresponding relationship between the outer elicet state and the intrinsic state, and provide a method of querying each guest order. The inherent state represents the type of dishes, and the external state is the dishes. A let us first take a look at the realization of simple enjoyment. First look at the definition of the abstract enjoys role: Interface Menu

{

/ / The implementation class must implement the method of setting up internal and external relationships

Public void setPersonMenu (String Person, List List);

/ / The method of implementing the implementation class must implement the intrinsic state corresponding to the exemplary state

Public List FindPersonMenu (String Person, List List);

}

This is a specific enjoys role:

Class PersonMenu Implements Menu

{

PRIVATE STRING DISH;

/ / In the constructor, the intrinsic state is added.

Public PersonMenu (String Dish) {

THIS.DISH = DISH;

}

Public synchronized void setPersonMenu (String Person, List List)

{

List.Add (Person);

List.Add (Dish);

}

Public List FindPersonMenu (String Person, List List)

{

List dishlist = new arraylist ();

Iterator it = list.iterator ();

While (it.hasnext ())

{

IF (persu.equals ((string) it.next ())))

Dishlist.add (it.next ());

}

Return dishlist;

}

}

Enjoy the role of the yuan factory, this is the key, everyone pays attention!

Class FlyweightFactory

{

Private map mAnulist = new hashmap ();

Private static flyweightfactory factory = new flyweightfactory ();

// The single example mode is also used to enable factory objects only generate a factory instance.

PRIVATE FLYIGHTFACTORY () {}

Public static flyweightfactory getInstance ()

{

Return Factory;

}

// This is the different way you enjoy the yuan model with the factory model! !

Public Synchronized Menu Factory (String Dish)

{

// Judgment If the intrinsic state already does not regenerate, but use the original, otherwise regenerate

IF (Menulist.Containskey (Dish))

{

Return (Menu) Menulist.get (Dish);

} else {

Menu Menu = New Personmenu (Dish);

Menulist.Put (Dish, Menu);

Return Menu;

}

}

// Take the verification, don't really produce an object

Public int getNumber ()

{

Return Menulist.size ();

}

}

We use the customer program to test it.

Class Client

{

PRIVATE Static FlyweightFactory Factory;

Public static void main (string [] args)

{

List list1 = new arraylist (); factory = flyweightfactory.getInstance ();

Menu List = Factory.Factory ("Pepper Potato");

List.setPersonMenu ("Ai92", LIST1);

List = factory.factory ("Red Burning Meat");

List.setPersonMenu ("Ai92", LIST1);

List = factory.factory ("Di Fang Fang");

List.setPersonMenu ("Ai92", LIST1);

List = factory.factory ("Di Fang Fang");

List.setPersonMenu ("Ai92", LIST1);

List = factory.factory ("Red Macadquet");

List.setPersonMenu ("Ai92", LIST1);

List = factory.factory ("Red Burning Meat");

List.setPersonMenu ("Ai921", LIST1);

List = factory.factory ("Red Macadquet");

List.setPersonMenu ("Ai921", LIST1);

List = factory.factory ("Di Fang Fang");

List.setPersonMenu ("Ai921", LIST1);

System.out.println (Factory.getNumber ());

List list2 = list.findpersonmenu ("ai921", list1);

Iterator it = list2.iterator ();

While (it.hasnext ())

{

System.out.println ("" it.next ());

}

}

}

This uses a simple enjoyment mode to implement these functions, but is you discovered that when a person, is it very inconvenient to use it? This situation is just in line with the use of composite enjoys mode: each of the simple enjoys included in the composite enchanting roll has the same amount, and these simple enclosed metapulsical states are often different. Since the composite element mode cannot be shared, there is no problem with the internal and external state. Therefore, in the composite enjoys, we do not have to implement the methods in the abstract enjoys, so this is a transparent synthetic pattern. Then I will implement it based on the basis of the above case. First, you must implement a composite enchantive role: Class PersonMenumuch Implements Menu {Private Map MAP Menulist = New HashMap (); Public PersonMenumuch () {} // Add a new simple product object public void address (String Key, Menu Menu) { Menulist.put (key, menu);} // Two ods PUBLIC SYNCHRON, LIST LIST) {} public list FindPersonMenu (String Person, List List) {list nothing = null; return nothing;} } Add a method to the factory method to achieve overload. Public menu factory (string [] dish) {PersonMenumuch Menu = new personumuch (); string key = null; for (int i = 0; i

This way I will use an example of using an example in detail. If you still don't quite understand, please reimburse the definition and structure of the previous. Only the combination of the two is good to experience the intention of enjoying the yuan. Five, use advantages and disadvantages

The advantage of enjoying the element is that it can greatly reduce the number of objects in memory; and bringing its shortcomings in order to do this: it makes the system logic complicates, and the system has affected the system to a certain extent. speed.

So you must remember to use the conditions of the enjoyment element:

1) There is a large number of objects in the system, and they reduce the efficiency of the system.

2) The status of these objects can separate both the inside and outside of the required.

The division of the external state and the intrinsic state and the correspondence of the relationships are also very valued. Only by dividing internal and outside can make the intrinsic state to play its own effect; if it is divided, in the worst case, the object in the system is not reduced! The maintenance of the correspondence between the two is also a certain space (of course, this is much smaller than the shared object) and time, can say that the energy mode is the time of use. In the GOF book, the B tree is used to find optimization.

Six, summary maybe you have to sigh: this is not necessarily complicated! This is not recognized, maybe because of its complexity, the actual application is not a lot, this is what we are more unable to see his true face. However, the energy mode is not a chicken rib. Its essence - sharing is very good for our system optimization, and this kind of thought is more and more applications, this should be applying to the application of the enjoys. If you have already appreciated the essence of the enjoys, then you have mastered your grade model!

I have finished the enjoys a yuan model. I don't know if I understand it. I hope that everyone can refer to it and make progress together! In fact, I always want to use an example in actual system or in practice to explain the yuan model, but after all, my work experience is too small! ! So I wanted to find some inspiration online, but I didn't find anything, so I used a metaphor for the use of a metaphor. If you have a deep understanding, please have to enlighten me! !

转载请注明原文地址:https://www.9cbs.com/read-78171.html

New Post(0)