Design Mode: flyweight)

Source: Internet
Author: User

Abstract:

1. This article will introduce in detail the principles of the metadata mode and the Application in actual code, especially the Android system code.

Outline:

1. Introduce the metadata Mode

2. Introduction to the concept and advantages and disadvantages of the shared Element Model

3. Application of the enjoy mode in Android source code

1. Start with a field:

Gg sends at least one text message to mm every day, And before going to bed every day, there will be one text message, which is often a trivial matter and a bit of emotional talk. In the first month, GG was still happy with this. Over time, he also felt bored when talking about it many times, what is even more intolerable is the repeated input of these emotional words each time. Gg told his friend K about this problem, K said, "You stupid, why don't you store some of your frequently used words on your mobile phone, you can use it directly when you want to use it. "When you hear it, silly Gg immediately feels that he has been overwhelmed, so he immediately saves it in his cell phone." Baby, good night "," you are my angel "," Baby, I love you forever "and other words. (From the android big talk Design Model)

2. Enjoy Mode Introduction 2.1 What is yuan Mode?

To save memory resources, you can manage duplicate instances in a unified manner (in combination with the factory mode). Generally, objects are referenced only when no new instances are created. Flyweight is a sports term used to represent lightweight objects. Flyweight, the flying weight, indicates that using it will make the code "lighter" (referring to memory consumption.

What are the benefits of the 2.2 yuan sharing model?

As mentioned above, the biggest and only benefit is: "light ". The metadata can save the memory consumption of duplicate instances. Here are two classic examples.

1. display data with 26 English letters on the dot matrix. When we use them, if we create a new letter instance every time we use them, the memory waste is very serious. We can easily think of creating an instance for the 26 lattice data entries and managing it with a class. When users need to use these instances, they can be referenced to greatly save memory consumption.

2. Painting. If the images I can draw are limited (circle, rectangle, prism, trapezoid, etc.), painting is to continuously map these images. When I draw a picture with thousands of patterns, the enjoy mode becomes a good solution to reduce memory consumption. We can create only one instance for all fixed images. When you want to draw images, you can use them to reference "painting.

However, there is a problem with this painting example: the positions, sizes, and colors of these independent images are different, and there is only one instance. Isn't it all squeezed out like this? Here is the metadata mode.KeyPlace: distinguish between the inner state and the external state. Simply put, a part (image) is shared (called internal storage or internal status), and a part (size, location, color) is not exclusive (called external storage or external status ). By adding this concept, the metadata sharing mode is much more flexible.

3. Source Code practice: 3.1 string :

I did not expect it! String uses the metadata mode. In fact, I did not expect it. In my personal understanding, it is better to say that the string uses the metadata mode to use its idea. After all, its implementation is not through the living Java code. Let's take a look:

String s0=”abc”;String s1=”abc”;String s2=”a” + “bc”;System.out.println( s0==s1 );System.out.println( s0==s2 );

 

Result:

truetrue

We all know that string is an object (not a basic type, the same below), and the object = is compared with the memory to which it points. If two objects point to the same data, they are equal (the Java language does not support overloading, so there is no exception ).

But shouldn't the above statement be three independent data segments? The constant pool is involved here.

The constant pool refers to the data that is identified during the compilation period and saved in the compiled. Class file. It includes constants in classes, methods, interfaces, and other fields, as well as string constants. These strings are the same constant strings for the compiler, so the compiler simplifies them into a piece of data, thus optimizing memory usage. This is exactly the same as the concept of the Yuan-sharing model.

If we write:

String s0=”abc”;String s1= new String(“abc”);System.out.println( s0==s1 );

Result:

false

Why? Because the right side of the S1 equal sign is not a constant string, but an instantiation operation, the compiler does not recognize this non-static thing. This also shows that the metadata needs to be managed by a dedicated class, otherwise the above situations will not apply. Generally, factory is used.

3.2 sqlitecompiledsql :

(Refer to Android design patterns series (6)-SDK Source Code enjoy the Yuan mode http://www.cnblogs.com/qianxudetianxia/archive/2011/08/10/2133659.html)

The use of sqlitecompiledsql in Android is a typical implementation of many database systems. Starting from the application, through various database operations, we do not know how many queries are performed, and some of these operations have the same SQL statements, these compiled SQL compilation objects are actually the same and can be shared and shared, but they are actually cache objects. Sqlitecompiledsql is such a metadata object to be shared.

UML diagram:

Among them, sqlitecompiledsql is the managed metadata object, mainly the internal status SQL statement:

class SQLiteCompiledSql {    private String mSqlStmt = null;    native_compile(sql);    native_finalize();}

The object is only an instance that stores fixed content. The essence of the object is in the factory that manages the object.

Sqlitedatabase is the factory used to manage the object, and mcompiledquerie is the container used to store the object. It is usually stored using hashmap (a substitute for hashtable, detailed http://oznyang.iteye.com/blog/30690. This method greatly reduces the creation of SQL compilation objects and improves the performance of database operations.

public class SQLiteDatabase{    Map<String, SQLiteCompiledSql> mCompiledQueries = Maps.newHashMap();    SQLiteCompiledSql getCompiledStatementForSql(String sql) {        SQLiteCompiledSql compiledStatement = null;        boolean cacheHit;        synchronized(mCompiledQueries) {           if (mMaxSqlCacheSize == 0) {            return null;           }            cacheHit = (compiledStatement = mCompiledQueries.get(sql)) != null;       }        if (cacheHit) {        mNumCacheHits++;        } else {            mNumCacheMisses++;        }        return compiledStatement;    }    private void deallocCachedSqlStatements() {        synchronized (mCompiledQueries) {            for (SQLiteCompiledSql compiledSql : mCompiledQueries.values()) {               compiledSql.releaseSqlStatement();            }            mCompiledQueries.clear();        }    }    void addToCompiledQueries(String sql, SQLiteCompiledSql compiledStatement) {    //省略具体代码    }}

The general Yuanyuan factory has the following structure:

Hashmap: used for storage (just like the constant pool of string)

Get method: Get metadata Object Reference

Add method: adds a new object to enjoy the metadata for initialization, which is not accessible to users. There are also more flexible metadata sharing modes that will dynamically increase the metadata objects not available in hashmap (the design mode is dead, and the code written by a person is live, and how to use it all depends on everyone ).

Dealloc method: releases all the metadata objects. Java has its own memory reclaim mechanism. This is optional.

Copyright. For more information, see the source:

Http://www.cnblogs.com/sickworm/p/4016026.html

Design Mode: flyweight)

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.