Prototype mode (Prototype) on android and design patterns

  • The prototype mode is generally implemented by clone, and the exact same data as this object is obtained by copying.
  • clone is divided into shallow copy and deep copy. Shallow copy only backs up some value variables, such as int, float, double, etc. For reference variables, it only copies a reference. If the value of this application is changed, other shallow copy references Variables will change; in the case of a deep copy, a copy of both the value variable and the reference variable will be added, and the cloned objects will not affect each other.
  • The emergence of clone is because the complexity and resource consumption of object creation may be much higher than that of clone; whether to use clone or new can only be determined after performance testing, because the possible performance is not necessarily less than the creation of new.
  • The specific use of prototype mode in android, such as ThreadLocal:
    1. We know that the core mechanism of Handler includes Message, MessageQueue, Looper, ThreadLocal, please refer to another blog post: http://blog.csdn.net/wangqiubo2010/article/ details/79465606
    2. ThreadLocal ensures that there is only one MessageQueue and Looper in each Handler. The specific reason is that a ThreadLocalMap inner class is defined in ThreadLocal, and ThreadLocal.ThreadLocalMap is instantiated in the thread Thread, so it is equivalent to backing up a ThreadLocalMap object for each thread, then the variables in the thread will only be visible to each site. In this way, each thread backs up one of its own variables, which solves the problem of multi-threaded access.
    3. The idea of ​​​​implementing multi-thread thread safety in ThreadLocal can be regarded as an implementation method of the prototype mode. Although it is not implemented by inheriting clone, it is also a prototype mode implemented by copying the idea.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324791859&siteId=291194637