Android Design Mode

Source: Internet
Author: User
Tags iterable

Introduction

Many problems may occur in the process of discovering and solving problems during project development, such as repeated occurrence and the legacy of a specific problem. The essence of these problems is the design model. Record the knowledge points of the design model today.

Content

In java and other object-oriented design patterns, there are six main relationships between classes: dependency, association, aggregation, combination, inheritance, and implementation. Their Coupling Degree increases sequentially.

Dependency:
For two relatively independent objects, when one object is responsible for constructing an instance of another object or dependent on the service of another object, the two objects are mainly dependent on each other.
Link:
It can be divided into one-way Association and two-way Association. In java, unidirectional Association is represented by Class B Used in Class A, where class B is A member variable of Class. Bidirectional Association: Class A uses Class B as the member variable, and Class B also uses Class A as the member variable.
Aggregation relationship:
It is a type of association relationship, and the coupling degree is stronger than the association. Their code performance is the same, only in terms of semantics: the objects of the Association relationship are mutually independent, there is an inclusive relationship between the objects of the aggregation relationship, and they are the "Whole-individual" relationship.
Combination:
Is a strongly coupled Association. A class with a composite relationship represents the association between "Whole-part", and "whole" is responsible for the life cycle of "part". They are co-occurrence and co-occurrence; and the "part" exists independently.
Inheritance:
Represents the parent-child relationship between a class or an interface.
Implementation:
Indicates the method that a class implements one or more interfaces.


Design principles

Key Points Definition Description
Single Responsibility Principle There should be no more than one cause of class change. In general, a class is only responsible for one responsibility. Problem cause: Class T has two different responsibilities: Responsibility P1 and responsibility P2. When the class T needs to be modified because of the change in the responsibility P1 requirement, it may lead to the failure of the originally running responsibility P2 function.

Solution: Follow the single responsibility principle. Create two classes T1 and T2 respectively, so that T1 completes the responsibility P1 function, and T2 completes the responsibility P2 function. In this way, when the class T1 is modified, the responsibility P2 will not be at risk of failure. Similarly, when the class T2 is modified, the responsibility P1 will not be at risk of failure.
Rys replacement principle Definition 1: If o1 is an object of Type T1, there is an object of Type T2 o2, so that when all program P defined by T1 is replaced by o2 for all object o1, the behavior of program P does not change, so Type T2 is the child type of Type T1.
Definition 2: all objects that reference the base class must be transparently used.
Problem: There is A function P1, which is completed by Class. Now you need to extend the feature P1. The extended feature is P, where P is composed of the original feature P1 and the new feature P2. New function p is completed by subclass B of Class A. When new function P2 is completed, subclass B may fail the original function P1.

Solution: when using inheritance, follow the Lee's replacement principle. When Class B inherits Class A, in addition to adding A new method to complete the new function P2, try not to override the method of parent class A, and try not to reload the method of parent Class.
Dependency inversion principle High-level modules should not depend on low-level modules, both of which should depend on their abstraction; abstraction should not rely on details; details should rely on abstraction. Problem: Class A directly depends on Class B. To change Class A to dependent Class C, you must modify the code of Class. In this scenario, Class A is generally A high-level module responsible for complex business logic; class B and class C are low-level modules responsible for basic atomic operations; if Class A is modified, it brings unnecessary risks to the program.

Solution: Change Class A to dependent interface I. class B and class C implement interface I. Class A indirectly associates with Class B or Class C through interface I, this greatly reduces the chance of modifying Class.
Interface isolation principle The client should not rely on interfaces that it does not need; the dependency of one class on the other class should be built on the smallest interface. Problem cause: Class A relies on Class B through interface I, and class C relies on Class D through interface I. If interface I is not the smallest interface for Class A and Class B, then class B and class D must implement the methods they do not need.

Solution: Split bloated interface I into several independent interfaces. Class A and Class C establish dependencies with the interfaces they need. That is, the interface isolation principle is adopted.
Dimit Law An object should have a minimum understanding of other objects. Problem: The closer the relationship between classes, the greater the coupling degree. When a class changes, the greater the impact on the other class.

Solution: Minimize coupling between classes.
Principle of opening/closing A software entity, such as classes, modules, and functions, should be open to extensions and closed to modifications. Problem cause: During the software life cycle, errors may be introduced to the Old Code when the original code of the software needs to be modified due to changes, upgrades, maintenance, and other reasons, it may also cause us to have to refactor the entire function and re-test the original code.

Solution: when the software needs to change, try to implement changes by extending the behavior of the software entity, rather than modifying the existing code.
     

Design Mode

Key Points Definition Description
Singleton Mode Make sure that a class has only one instance, and instantiate it and provide the instance to the entire system. Considerations for Singleton mode:
Only the methods provided by the singleton class can be used to obtain the singleton object. Do not use reflection. Otherwise, a new object will be instantiated. Do not perform dangerous operations to disconnect a singleton class object from static reference in the class. Pay attention to thread security issues when using shared resources for multiple-threaded use cases.
Factory method mode Defines an interface used to create objects so that the subclass determines which class to instantiate. The factory method delays the instantiation of a class to its subclass. In the factory method mode, the core factory class is no longer responsible for the creation of all objects, but the specific creation work is handed over to the subclass. This core class changes and becomes an abstract factory role. It is only responsible for providing the interface that must be implemented by the specific factory subclass without touching the details of which class should be instantiated.
Abstract Factory Model Provides an interface for creating a set of related or interdependent objects without specifying their specific classes. The factory method mode is applicable in the following cases:
(1) When a class does not know the class of the object it must create.
(2) When a class wants its subclass to specify the object it creates.
(3) When the class delegates the responsibility of creating an object to one of multiple help sub-classes, and you want to localize the information of which help sub-classes are proxies.
Template Method Mode Defines the framework of an algorithm in an operation, and delays some steps to the subclass so that the subclass can redefine some specific steps of the Algorithm without changing the structure of the algorithm. Subclass can replace the variable part of the parent class, but it cannot change the top-level Logic represented by the template method.
When defining a new subclass, you should not think about the control process, but the "responsibility" approach. In other words, we should consider which operations must be replaced, which can be replaced, and which cannot be replaced. Using the template mode can clarify these responsibilities.
Builder Mode Separates the construction of a complex object from its representation, so that different representations can be created during the same construction process. Difference from Abstract Factory: In the builder mode, there is a mentor who manages the builder. the user is in contact with the mentor, and the mentor contacts the builder to get the product. That is, the construction mode can enforce a step-by-step construction process.
The construction mode encapsulates complex internal creation in the Internal. For external callers, they only need to pass in the builder and construction tool. The caller does not need to care about how the internal creation is finished.
This mode is used in Java applications.
Proxy Mode Provides a proxy for other objects to control access to this object. A proxy means that one person or institution takes action on behalf of another person or institution. In some cases, a client does not want or cannot directly reference an object, and the proxy object can play a mediation role between the client and the target object.
Prototype Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

The prototype mode requires that the object implement an interface that can "clone" itself, so that you can create a new instance by copying an instance object itself. In this way, you no longer need to care about the type of the instance when creating new objects through the prototype instance. As long as you implement the clone method, you can use this method to obtain new objects, instead, you do not need to create it through new.
To clone an object in depth in Java, You can first implement the Serializable interface for the object, and then write the object (actually just copying the object) to a stream (serialization ), then, the object can be re-built by reading back from the stream (deserialization.

Advantages of Prototype
The prototype mode allows you to dynamically change the implementation type at runtime. During the running of the prototype mode, the customer can register the implementation types that conform to the prototype interface, or dynamically change the specific implementation types. It seems that the interface has not changed, however, another class instance is running. Because cloning a prototype is similar to instantiating a class.

Disadvantages of Prototype
The main disadvantage of the prototype mode is that each class must have a clone method. To assign a clone method, you need to consider the functions of the class comprehensively. This is not difficult for all new classes, but not necessarily easy for existing classes, especially when a class references indirect objects that do not support serialization or reference a circular structure.
Intermediary Mode A series of object interactions are encapsulated with an intermediary object. The intermediary makes the interaction between objects do not need to be displayed, so that the coupling is loose and the interaction between them can be changed independently.

Advantages of intermediary Mode
Proper use of the intermediary mode can avoid excessive coupling between colleague classes, so that each colleague class can be used relatively independently.
The intermediary mode can be used to convert one-to-many associations between objects into one-to-one associations, making the relationships between objects easy to understand and maintain.
The intermediary mode can be used to abstract the behavior and collaboration of objects and flexibly process the interaction between objects.
Applicable scenarios
In object-oriented programming, a class is bound to be dependent on other classes, and completely independent classes are meaningless. It is also quite common that a class depends on multiple classes at the same time. In this case, one-to-many dependencies are rational, the proper use of the intermediary mode can clear the original messy object relationship, but abuse may result in reverse effects. Generally, the intermediary mode is considered only when the relationship between colleague classes is in a mesh structure. The mesh structure can be changed to a star structure, so that the relationship between colleagues and classes becomes clearer.
Intermediary mode is a common mode and a mode that is easy to abuse. In most cases, the relationships between colleague classes are not complex to messy mesh structures. Therefore, in most cases, the inter-object dependency can be encapsulated inside the colleague classes, there is no need to introduce the intermediary mode. Misuse of the intermediary model only makes things more complicated.
Command mode Intent: encapsulate a request as an object so that different requests can be used to parameterize the customer, queue requests or record logs, and support auditable operations
Motivation: Separate the "requested object" and "receiving and executing the request object.
Common applications:
1. Work queue, thread pool, and schedule
2. Log request (System Recovery)
Key points:
1. In command mode, the requested object and the requested object are decoupled.
2. the decoupled two are communicated through command objects. The command object encapsulates the receiver and one or more actions.
3. The caller sends a request by calling execute () of the command object, which will make the recipient's action called
4. The caller can accept the command as a parameter, or even dynamically execute it at runtime.
5. commands can be undo. an undo () method is implemented to return to the status before execute () is executed.
6. Macro commands are a simple extension of commands, allowing you to call multiple commands. The macro method also supports revocation.
7. In actual operations, it is common to use the "smart" command object, that is, directly implementing the request, rather than entrusting the work to the recipient (disadvantage ?)
8. commands can also be used to implement logging and transaction systems.
Responsibility Chain Model So that multiple objects have the opportunity to process the request, thus avoiding the coupling relationship between the request sender and the receiver. Connect these objects into a chain and pass the request along the chain until an object processes it. A pure responsibility chain model requires that a specific handler object can only select one of the two actions: one is to take responsibility, but to push the responsibility to the next house. It is not allowed that a specific processor object transfers down the responsibility after assuming part of the responsibility.
In a pure mode of responsibility chain, a request must be received by a handler object. In an unpure mode of responsibility chain, A request cannot be received by any receiving end object.
The actual examples of the pure responsibility chain mode are difficult to find. Generally, the examples are the implementation of the pure responsibility chain mode. Some people think that the responsibility chain is not the responsibility chain model at all, which may be justified. However, in the actual system, it is difficult to find a pure responsibility chain. If the responsibility chain is not purely the responsibility chain model, the responsibility chain model will not make much sense.
Decoration Mode Also known as the Wrapper mode, the decoration mode extends the object functions in a transparent way to the client, and is an alternative to the inheritance relationship. Differences between the decoration mode and class inheritance:
1) The decoration mode is a dynamic behavior that combines existing classes at will, while class inheritance is a static behavior. What kind of behavior is a class defined, what kind of functions does the object of this class have and cannot be changed dynamically.
2) The decoration mode extends the functions of objects without increasing the number of classes. The class inheritance extension is a class function. In the inheritance relationship, if we want to add the function of an object, we can only add two methods in the subclass through the inheritance relationship.
3) Comparison between decoration and inheritance:
4) The decoration mode dynamically extends the function of an object without changing the original class file and using inheritance. It creates a packaging object, that is to say, the decoration is really an object.
5. The decoration mode delegates the call to the client to the decorated class. The key of the decoration mode is that the extension is completely transparent.
Rule Mode Define a set of algorithms, encapsulate each algorithm, and make them interchangeable.
The advantage of the Policy mode is that you can dynamically change the behavior of objects.
Policy mode is an object behavior mode. It encapsulates an algorithm into an independent class with a common interface for mutual replacement. The policy mode allows the algorithm to change without affecting the client. Generally, the policy mode is applicable when an application needs to implement a specific service or function, and the program has multiple implementation methods.
Adapter Mode Provide interfaces to customers based on the services provided by existing classes to meet customers' expectations.

The purpose of the adapter mode is to change the source interface so that the target interface is compatible. Default adaptation has a slightly different purpose. It is a mediocre implementation provided to facilitate the establishment of a non-mediocre adapter class.
Advantages of the adapter Mode
Better reusability
The system needs to use existing classes, and such interfaces do not meet the requirements of the system. The adapter mode enables better reuse of these functions.
Better scalability
When implementing the adapter function, you can call your own developed functions to naturally expand the system functions.
Disadvantages of adapter Mode
Using too many adapters will make the system messy and difficult to grasp as a whole. For example, we can see that the called a interface is actually adapted to the implementation of B interface internally. If there are too many systems, this would be a disaster. Therefore, if not necessary, you can directly refactor the system without using the adapter.
Iterator Mode Provides a method to access each element in a container object without exposing the internal details of the object. In jdk, there are two Iterator-related interfaces: Iterator and Iterable.
Iterator: Iterator. Iterator and its sub-classes are usually the structure and method of the Iterator;
Iterable: iteratable. Other classes that want to use the iterator function, such as AbstractList HashMap, need to implement this interface.
Combination Mode The object is combined into a tree structure to represent the 'partial-uniyun' hierarchy. The combination mode ensures consistency between the use of a single object and a composite object.

By implementing an (inherited) unified interface (abstract class), the caller is consistent with the operations on a single object and the composite object.
By implementing the combination mode, the caller is consistent with the operations on the combined object and the operations on a single object. Callers can call related methods to implement functions without having to worry about the combination object or the specific structure of the combination object.
Observer Mode Defines a one-to-many dependency between objects, so that when each object changes state, all objects dependent on it will be notified and automatically updated.

The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.
In the JAVA. util library of the java language, an Observable class and an Observer interface are provided to support the Observer mode of the JAVA language.
Facade Mode External communication with a sub-system must be performed through a unified facade object. Advantages of the facade mode:
● Loose coupling
The facade mode loose the coupling relationship between the client and subsystem, making it easier to expand and maintain modules within the subsystem.
● Easy to use
The facade mode makes the subsystem easier to use. The client no longer needs to understand the internal implementation of the subsystem, nor need to interact with the internal modules of many subsystems. It only needs to interact with the portal class.
● Better access levels
The rational use of Facade can help us better classify access layers. Some methods are external to the system, and some methods are used inside the system. The functions that need to be exposed to the external are concentrated in the facade, which facilitates the use of the client and hides the internal details.
Memorandum Mode Capture the internal state of an object without compromising encapsulation, and save the state outside the object. In this way, the object can be restored to the previously saved state. A memorandum object is an object used to store snapshots of another object's internal state. The purpose of the memorandum mode is to Capture, externalize, and store the status of an object without damaging the encapsulation, in this way, this object can be restored to the stored state when appropriate in the future. The memorandum mode is often used together with the command mode and iteration submode.
Visitor Mode Encapsulate some operations that act on each element in a data structure. It can define new operations that act on these elements without changing the data structure.
The visitor mode is the behavior mode of objects. The visitor mode aims to encapsulate operations that are applied to certain data structure elements. Once these operations need to be modified, the data structure that accepts the operation can remain unchanged.
Advantages of visitor Mode
Good scalability
You can add new functions for elements in the object structure without modifying the elements in the object structure.
Good reusability
Visitors can be used to define the general functions of the entire object structure, thus improving the degree of reuse.
Separate irrelevant Behaviors
Independent behaviors can be separated by visitors, and relevant behaviors can be encapsulated together to form a visitor. In this way, each visitor has a single function.

Disadvantages of visitor Mode
It is difficult to change the object structure.
It is not suitable for situations where classes in the object structure change frequently. Because the object structure changes, the visitor's interface and visitor's implementation must change accordingly, and the cost is too high.
Destroy Encapsulation
The visitor mode usually requires the object structure to open internal data to the visitor and ObjectStructrue, which breaks the encapsulation of the object.
Status Mode When the internal state of an object changes, it is allowed to change its behavior. This object seems to have changed its class.
The State mode allows an object to change its behavior when its internal state changes. This object looks like a class that has changed it.
 
Interpreter Mode Given a language, it defines a representation of its syntax and an interpreter that uses this representation to explain sentences in the language.  
Meta Mode Reuse existing objects in our memory to reduce the performance consumption of the system to create object instances.

In boxing, Flyweight refers to the most lightweight model, that is, "Fly magnitude" or "rainfall level". Here we use the free translation of "Enjoy yuan mode", because it can better reflect the intention of the model. The metadata mode is the object structure mode. The metadata mode supports a large number of fine-grained objects efficiently in a shared manner.
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 enabling shared object sharing is to differentiate the Internal State and External State ).
Bridge Mode Decouples abstraction and implementation so that the two can change independently.
The purpose of the bridge mode is to "decouple abstract actions and Implementation so that the two can change independently ".
A typical example of the Bridge Mode in Java applications is the JDBC driver. JDBC provides a common interface for all relational databases. An application system dynamically selects an appropriate drive and sends commands to the database engine through the drive. This process delegates the abstract role behavior to the role.
     

Project

Wrote an Android project to reflect the design pattern in 23, Project




Test code:

Public void onClickSingleMode (View view) {// SingleMode for a single instance. getInstance ();} public void onClickFactoryMethodModel (View view) {// factory method IProduct iProduct = new FactoryMethodModel (); iProduct. productMethod (); iProduct = new Tree (); iProduct. productMethod ();} public void onClickAbstractFactoryModel (View view) {// Abstract Factory AbstractFactoryModel. test ();} public void onClickTemplateMethodModel (View view) {// template method mode TemplateMethodModel. test ();} public void onClickBuilderMode (View view) {// builder mode BuilderMode. test ();} public void onClickProxyMode (View view) {// proxy mode ProxyMode. test ();} public void onClickCloneMode (View view) {// prototype mode CloneMode. test ();} public void onClickIntermediaryModel (View view) {// IntermediaryModel in intermediary mode. test1 (); IntermediaryModel. test2 ();} public void onClickCommandMode (View view) {// command mode CommandMode. test ();} public void onChainOfResponsibilityModel (View view) {// chain of responsibility mode ChainOfResponsibilityModel. test ();} public void onClickDecorativeMode (View view) {// DecorativeMode. test ();} public void onClickStrategyMode (View view) {// Strategy Mode StrategyMode. test ();} public void onClickIteratorModel (View view) {// mode IteratorModel. test ();} public void onClickCombinationMode (View view) {// composite mode CombinationMode. test ();} public void onClickObserverMode (View view) {// observer mode ObserverMode. test ();} public void onClickWindowMode (View view) {// WindowMode in facade mode. test ();} public void onClickMemoMode (View view) {// memorandum mode MemoMode. test ();} public void onClickVisitorMode (View view) {// visitor mode VisitorMode. test ();} public void onClickStateModel (View view) {// status mode StateModel. test ();} public void onClickParserMode (View view) {// ParserMode in interpreter mode. test ();} public void onClickFlyweightMode (View view) {// enjoy the metadata mode FlyweightMode. test ();} public void onClickBridgeMode (View view) {// Bridge Mode BridgeMode. test ();}


Summary

If the design pattern is rarely used in the coding design career, the main reason is that the understanding of the design pattern is not enough and the problem is not known.
Because the problem cannot be correctly analyzed and understood, it is certainly impossible to solve the problem well.


Project download

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.