Java design pattern-enjoy the metadata Pattern

Source: Internet
Author: User
Structure of the metadata Mode

The metadata mode uses a shared object to avoid overhead of a large number of objects with the same content. The most common and intuitive overhead is the memory loss. The key to achieving shared object sharing is differentiation.Internal State)And

External state ).

An internal state is stored inside the object, and does not change with the environment. Therefore, a shared object can have an internal state and can be shared.

An external State Changes and cannot be shared as the environment changes. The external status of the object must be saved by the client. After the object is created, the object must be uploaded to the object. External

The inherent status of the object is independent of each other.

Benefits of the metadata mode: reduces the number of objects and saves memory space.

Disadvantage of the metadata-Sharing Mode: maintaining shared objects requires additional overhead (using a thread to maintain garbage collection ).

The essence of the Sharing Model: Separation and sharing

When to use the metadata mode:

If an application uses a large number of fine-grained objects, you can use the metadata mode to reduce the number of objects.

If you use a large number of objects, resulting in high storage overhead, you can use the enjoy mode to reduce the number of objects and save memory.

If most States of an object can be changed to the external state, you can use a metadata object to separate the external State from the internal state.

The metadata mode can be dividedSimple metadata ModeAndCompound metadata Mode.

Simple metadata Mode

In the simple metadata mode, all metadata objects can be shared.

The simple metadata mode involves the following roles:
Abstract element (flyweight) Role: provides an abstract interface to specify the methods to be implemented for all specific element roles.

Concreteflyweight: implements the interface specified by the abstract metadata role. If there is an inner state, it must provide storage space for the inner state.

Flyweightfactory role: this role is responsible for creating and managing the metadata. This role must ensure that the object can be shared by the system. When a client object calls

The metadata factory role checks whether there is a qualified metadata object in the system. If you already have the metadata, the metadata factory role should provide the existing metadata object. If the system does not have an appropriate metadata object

Then, you should create a suitable metadata object.

Well, let's just talk about the code. First, let's abstract a scenario:

The company's management and general employees have different permissions on employee information. The management layer can modify the employee's personal information. General employees can only view and cannot modify the personal information. If they modify the personal information without authorization, a prompt is displayed. The personal information of employees can be shared, but the functional scope and operation permissions can be modified by the management.

Abstract meta-role:

Public interface iflyweight {/*** identifies the passed security entities and permissions, whether to match the internal status of the object * The securityentity and permit parameters are external objects * @ Param securityentity * @ Param permit * @ return */Public Boolean match (string securityentity, string permit );}

Specific metadata roles:

Public class authorizationflyweight implements iflyweight {/*** internal object, security entity */private string msecurityentity;/*** internal object, permission */private string mpermit; public authorizationflyweight (string state) {string STR [] = state. split (","); this. msecurityentity = STR [0]; this. mpermit = STR [1] ;}@ overridepublic Boolean match (string securityentity, string permit) {If (msecurityentity. equals (securityentity) & mpermit. equals (Permit) {return true;} return false ;}}

Enjoy yuan Factory:

Public class flyweightfactory {Private Static flyweightfactory mfactory = new flyweightfactory (); Private flyweightfactory () {} public static flyweightfactory getinstance () {return mfactory ;} /*** cache multiple iflyweight objects */private Map <string, iflyweight> flymap = new hashmap <string, iflyweight> (); /*** get the metadata Unit * @ Param key * @ return */Public iflyweight getflyweight (string key) {iflyweight fly = flymap. get (key); If (fly = NULL) {fly = new authorizationflyweight (key); flymap. put (Key, fly) ;}return fly ;}}

Management tools for employee information:

Public class securitymanager {Private Static securitymanager manager = new securitymanager (); Private securitymanager () {} public static securitymanager getinstance () {return manager ;} /*** permission for storing logon users */private Map <string, collection <iflyweight> map = new hashmap <string, collection <iflyweight> (); public void Logon (string user) {collection <iflyweight> coll = querybyuser (User); map. put (user, coll);}/*** get all permissions of a person from the database ** @ Param user * @ return */private collection <iflyweight> querybyuser (string user) {collection <iflyweight> coll = new arraylist <iflyweight> (); For (string S: testdb. coll) {string STR [] = S. split (","); If (STR [0]. equals (User) {iflyweight fly = flyweightfactory. getinstance (). getflyweight (STR [1] + "," + STR [2]); Coll. add (FLY) ;}} return Coll ;} /*** determine whether a user has certain permissions on a security entity ** @ Param user * User * @ Param securityentity * security entity * @ Param permit * permission * @ return */ public Boolean haspermit (string user, string securityentity, string permit) {collection <iflyweight> coll = map. get (User); If (coll = NULL | Coll. size () = 0) {system. out. println (User + "is not logged on or does not have this permission... "); Return false;} For (iflyweight fly: Coll) {If (fly. match (securityentity, permit) {return true ;}} return false ;}}

Simulate a database to save employee information:

Public class testdb {public static collection <string> coll = new arraylist <string> (); static {Coll. add ("Zhang San, personnel list, View"); Coll. add ("Li Si, personnel list, View"); Coll. add ("Li Si, salary list, View"); Coll. add ("Li Si, salary list, modify"); For (short I = 0; I <3; I ++) {Coll. add ("Zhang San" + I + ", personnel list, View ");}}}

The specific implementation is implemented in this example based on Android. Java only writes a test class to implement it in main:

Securitymanager manager = securitymanager. getinstance (); manager. logon ("James"); manager. logon ("Li Si"); Boolean b1 = manager. haspermit ("Zhang San", "salary list", "View"); Boolean b2 = manager. haspermit ("Li Si", "salary list", "View"); Boolean B3 = manager. haspermit ("Zhang San", "personnel list", "View"); system. out. println ("b1 =" + B1); system. out. println ("b2 =" + b2); system. out. println ("B3 =" + B3 );

Running effect:

It can be seen from the database that Michael is an ordinary employee of personnel and can only view employees in the company. Michael has no permission to view employees' salaries. If B1 returns false, B3 returns true.

Li Si is a general personnel employee and financial supervisor. He can modify and query employee salaries and view employee information. B2 returns true.

If

Boolean B4 = manager. haspermit ("Wang Wu", "personnel list", "View ");

Because "Wang Wu" is not logged on, the prompt message is "No Logon or no permission ..."

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.