Android design mode

Source: Internet
Author: User
Tags iterable

Simple Introduction

There are many problems in the process of discovering problems and solving this problem in project development, such as repeated occurrences and the legacy of some problems, the essence of which is design pattern.

Record the knowledge points of design patterns today.


Content

In Java and other object-oriented design patterns, there are 6 main relationships between classes and classes. They are: dependency, association, aggregation, composition, inheritance, implementation.

Their coupling degree is increased in turn.

Dependency Relationship:
For two relatively independent objects, when an object is responsible for constructing an instance of an object, or if it relies on a service that has an object, the two objects are primarily dependent.
Association relationship:
is divided into one-way and two-way associations. In Java. A one-way association behaves as follows: Class A uses Class B. Where Class B is the member variable for Class A. The bidirectional association behaves as follows: Class A uses Class B as a member variable, and Class A is used as a member variable in Class B at the same time.


Aggregation relationships:
is a kind of association, the coupling degree is stronger than the association, their code performance is the same, only in the semantic difference: the relationship between the object is independent of each other, and the object of the aggregation relationship between the existence of an inclusive relationship. Between them is the "general-individual" interrelationship.


Composition Relationship:
is a stronger coupling relationship. A class that has a composition relationship represents the association of the "overall-part" relationship. "Overall" is responsible for the life cycle of the "part". There was a symbiotic death between them. and "partial" exists alone without any meaning whatsoever.
Inherited:
Represents a parent-child relationship between a class and a class (or interface and interface).


Realize:
Represents a method for a class to implement one or more interfaces.



Design principles

Points Defined Descriptive narrative
Single principle of responsibility Do not have more than one cause for class changes. In layman's terms, a class is responsible for only one responsibility.

The origin of the problem: class T is responsible for two different duties: responsibility P1, Responsibility P2. When a change of class T is required due to the P1 of a duty, it is possible to cause a problem with the function P2 the normal duties.



Solution: Follow the principle of single responsibility. Respectively, set up two classes T1, T2, so that the T1 finished the responsibility P1 function, T2 complete responsibility P2 function. Such When the class T1 is changed, the responsibility is not P2 the risk of the problem, and in the same vein, when the T2 is changed, the responsibility is not P1 the risk of the problem.

The principle of the Richter replacement Definition 1: Assume a O1 for each object of type T1. There are object O2 of type T2, so that all program P defined in T1 is replaced with O2 in all object O1, the behavior of program P has not changed. Then type T2 is a subtype of type T1.
Definition 2: All references to the base class must be able to transparently use objects of its subclasses.
The problem is: there is a functional P1, completed by Class A. It is now necessary to extend the function P1. The extended function is P, where p is composed of the original function P1 and the new function P2.

The new function p is finished by subclass B of Class A, then subclass B is at the same time when the new function is P2. May cause problems with the original function P1.

Workaround: Follow the Richter substitution principle when using inheritance.

When Class B inherits Class A, the addition of the new method is complete except for the addition of P2. Try not to override the parent class A method, and try not to reload the parent class A method.

Dependency Inversion principle High-level modules should not rely on lower-layer modules, both should rely on their abstraction. Abstraction should not depend on detail; detail should depend on abstraction. Problem Origin: Class A is directly dependent on class B. If you want to change Class A to dependency Class C, you must do so by changing the code of Class A.

In such a scenario, Class A is usually a high-level module, responsible for complex business logic, and Class B and Class C are low-layer modules that are responsible for basic atomic operations. If you change the Class A, it will bring unnecessary risk to the program.



Workaround: Change Class A to dependent interface I, Class B and Class C each implement interface I, Class A through interface I indirectly with Class B or Class C, it will greatly reduce the chance to change Class A.

Interface Isolation principle The client should not rely on interfaces that it does not need, and a class-to-class dependency should be based on the smallest interface. The problem is that class A relies on class B through interface I, and Class C relies on class D through interface I, assuming that interface I is not the smallest interface for Class A and Class B. Then Class B and Class D must implement methods that they do not need.



Workaround: Split the bloated interface I into separate interfaces. Class A and Class C are dependent on the interfaces they need, respectively. That is, using the interface isolation principle.

Dimitri Law An object should have a minimal understanding of other objects. The problem is: the closer the relationship between classes and classes, the greater the coupling, and the greater the impact on one class when a class changes.



WORKAROUND: Minimize the coupling between classes and classes.

Opening and closing principle A software entity such as classes, modules, and functions should be open to extensions. Turn off the changes.

The origin of the problem: in the software's life cycle, due to changes, upgrades and maintenance and other reasons need to change the original code of the software. Errors may be introduced into the old code, or we will have to refactor the entire function correctly, and need the original code to be tested again.

Workaround: When the software needs to change, as far as possible by extending the behavior of software entities to achieve change. Instead of changing the existing code to implement the change.

Design Patterns

The The
Points Defined Descriptive narrative
Single-Case mode Make sure that a class has only one instance, and instantiates itself and provides this instance to the entire system. Single-Case Mode considerations:
Singleton objects can only be obtained using the methods provided by the Singleton class. Do not use reflection, or a new object will be instantiated. Do not break a critical operation that breaks a static reference in a class object with an instance. Use a single instance of multithreading when using shared resources, pay attention to thread safety issues.
Factory method Mode Defines an interface that is used to create an object, so that subclasses decide which class to instantiate, and the factory method defers the instantiation of a class to its subclasses. In factory method mode, the core factory class is no longer responsible for the creation of all objects. Instead, give the details of the created work to the subclass.

This core class is transformed into an abstract factory role that is only responsible for the interfaces that the detailed factory subclass must implement. Without touching which class should be instantiated in such detail.

Abstract Factory mode Provides an interface for creating a set of related or interdependent objects without specifying their detailed classes. In the following cases, the factory method mode is applied:
(1) When a class does not know the class of the object it must create.
(2) When a class wants to specify the object it creates by its subclasses.


(3) When a class entrusts the responsibility of creating an object to one of several helper subclasses, and you want to put which helper subclass is the agent this information is localized.

Template method Mode Defines a framework for an algorithm in an operation, and delays some steps into subclasses. Enables subclasses to redefine some specific steps in the algorithm without altering the structure of the algorithm. Subclasses can displace the mutable parts of a parent class. But subclasses are not able to change the top-level logic represented by the template method.
Whenever a new subclass is defined, do not think in terms of the flow of control, but in accordance with the thinking of "responsibility". In other words, you should consider which operations must be replaced and which can be displaced. And which operations cannot be replaced. Using template mode can make these responsibilities clear.

Builder mode Separating the construction of a complex object from its representation allows the same build process to create different representations. The difference from the abstract factory: in the builder model, there is a mentor, the mentor who manages the builder, the user is contacted by the mentor, and the mentor contacts the builder to get the final product.

That is, the construction model is able to enforce a step-through construction process.


The build pattern is to encapsulate the complex internal creation inside. For external callers, only the builders and construction tools are required. The caller does not need to be concerned about how the interior is built to create the finished product.
This pattern is javamail used in Java applications.

Proxy mode Provides a proxy for other objects to control access to this object. The so-called agent, is a person or representative of the organization also has a person or organization take action.

In some cases. A customer does not want or cannot directly refer to an object. The proxy object can act as an intermediary between the client and the target object.

prototype mode Specifies the kind of object created with the prototype instance and creates a new object by copying the prototypes. The

Prototype pattern requires that an object implement an interface that can "clone" itself so that a new instance can be created by copying an instance object itself. Thus, creating a new object from a prototype instance eliminates the need to care about the type of the instance itself. By simply implementing a method of cloning itself, it is possible to acquire new objects in this way without having to create them through new. The
deeply clones an object in the Java language. It is often possible to make an object implement the Serializable interface, and then write the object (actually a copy of the object) into a stream (serialized), and then read it back from the stream (deserialize) to reconstruct the object. The advantage of the

prototype pattern
Prototype mode agrees to dynamically change the detailed implementation type at execution time. The

Prototype mode allows the client to register implementation types that conform to the prototype interface during execution, and to dynamically change the detailed implementation type. It seems that the interface does not change, but in fact it is already a different class instance.

The cloning of a prototype is similar to instantiating a class. Disadvantages of the



Prototype mode
Prototype mode The most basic disadvantage is that each class must be equipped with a clone method. Having a cloning method requires a holistic view of the functionality of the class, which is not very difficult for a new class. It is not necessarily easy for existing classes, especially when a class references an indirect object that does not support serialization, or when a reference contains a looping structure.

Mediator mode encapsulates a series of object interactions with a mediator object. Intermediaries do not need to show the interaction between the objects. This makes the coupling loose and can change the interaction between them independently. The advantages of the

Broker pattern
Proper use of the mediator pattern avoids over-coupling between colleague classes, making it possible to use them relatively independently between colleagues. The
uses the mediator pattern to transform a one-to-many association between objects into one-to-one associations. Make relationships between objects easy to understand and maintain. The
use the mediator pattern to abstract the behavior and collaboration of objects, and to manipulate the interaction between objects in a more flexible way.

applicable scenarios
        in object-oriented programming, a class must be dependent on other classes. It is meaningless to have a completely independent class.

A class that relies on multiple classes at the same time is also quite common, since there is a case where a one-to-many dependency has its justification. Proper use of the intermediary mode can make the original messy object relationship clear, but the assumption of abuse, it may be counterproductive.

In general, the use of the mediator pattern is only considered when there is a relationship between the type of colleague class that is a net structure. The ability to change the mesh structure into a star-like structure makes the relationship between colleague classes clearer. The
        Broker mode is a more frequently used pattern and a more easy-to-use model. In most cases, the relationship between colleague classes is not complicated by the chaotic network structure. Therefore, in most cases, it is possible to encapsulate the dependencies between objects within a colleague class. There is no need to introduce a mediator pattern. Abusing the broker model will only make things more complicated.

Command mode Intent: Encapsulates a request as an object, which allows the client to be counted with different requests. Queue or log the request. and support for actions that can be undone
Motivation: Separate the "requesting objects" and "the objects receiving and executing these requests".
Common applications:
1, Work queue, thread pool. Schedule
2. Log request (System Recovery)
Points:
1. The command mode decouples the object making the request from the object executing the request
2, in the decoupling between the two is through the command object to communicate. The command object encapsulates the recipient and one or a set of actions
3. The caller makes a request by invoking execute () of the Command object. This causes the receiver's actions to be called
4, the caller can accept the command as a parameter, even in the execution of the dynamic
5, the command can support revocation. The practice is to implement an undo () method to return to the state before execute () is executed
6, Macro command is a simple extension of the command, agree to invoke multiple commands. The macro method can also support undo
7, the actual operation. Non-common use of "smart" command objects, that is, the direct implementation of the request, rather than entrust the work to the recipient (the disadvantage?). )
8, command can also be used to implement the log and the thing system
Responsibility chain Model Enables multiple objects to have the opportunity to process requests, thus avoiding the coupling between the sender and receiver of the request. Link the objects to a chain and pass the request along this chain until an object has processed it.

A pure chain of responsibility model requires a detailed handler object to choose only one of two behaviors: one is to take responsibility, but to push the responsibility to the next person. Does not agree with the situation where a particular processor object has assumed a part of the responsibility and then transmitted the responsibility downward.


In a pure chain of responsibility mode, a request must be received by a handler object. In an impure chain of responsibility, a request can finally be received regardless of the receiving end object.
The actual sample of the pure responsibility chain pattern is very difficult to find, and the example that is generally seen is the realization of the impure responsibility chain pattern.

Some people feel that the impure chain of responsibility is not a chain of responsibility at all. This may make sense. But in the actual system, the pure responsibility chain is very difficult to find. Assuming that the adherence to the chain of responsibility is not the responsibility chain model, then the chain of responsibility model will not have much significance.

Decoration mode AKA Packaging (Wrapper) mode, which expands the functionality of the object in a transparent manner to the client. is an alternative to an inheritance relationship. The difference between the adornment pattern and the class inheritance:
1) Decoration mode is a dynamic behavior. Any combination of already existing classes. The inheritance of a class is a static behavior, and a class defines what kind of function the object of the class has and cannot be changed dynamically.


2) The decoration mode extends the function of the object, does not need to add the number of classes, and the class inheritance extension is the function of the class, in the inheritance relationship, suppose we want to add an object function, we can only through the inheritance relationship, in the subclass to add two methods.
3) Decoration and inheritance comparison chart:
4) Decorating mode is the ability to dynamically extend an object without changing the original class file and using inheritance, it is by creating a wrapper object, which is the object that is decorated to wrap.


5. Decoration mode delegates the call to the client to the decorated class. The key to decorating mode is that such an extension is completely transparent.

Policy mode Defines a set of algorithms. Encapsulate each algorithm and make them interchangeable.


The advantage of a strategy model is that you can dynamically change the behavior of an object.

The policy mode belongs to the object behavior pattern. Mainly for a set of algorithms, each algorithm is encapsulated in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client. Usually. Policy mode is useful when an application needs to implement a specific service or function. And the program is implemented in a variety of ways when used.
Adapter mode Provide interfaces to customers based on the services provided by existing classes to meet customer expectations.



The adapter mode is intended to change the interface of the source so that it is compatible with the target interface. The default adaptation is a slightly different intention. It is a trivial implementation provided to facilitate the creation of an extraordinary adapter class.

Advantages of Adapter Mode
Better reusability
The system needs to use the existing classes, and such interfaces do not meet the needs of the system. The adapter mode allows for better reuse of these features.
Better extensibility
When implementing the adapter function. Ability to invoke the features you have developed to naturally extend the functionality of the system.


Disadvantages of Adapter Mode
Excessive use of the adapter, will make the system very messy, not easy to grasp the overall. For example, clearly see the call is a interface. In fact, the interior is adapted to the implementation of the B interface, and a system assumes that there are too many cases. is a disaster.

It is therefore not very necessary to assume that the system can be refactored without the use of an adapter.

Iterator mode Provides a way to access individual elements in a container object without exposing the object's internal details. In the JDK, there are two interfaces associated with iterators: Iterator and Iterable
Iterator: Iterator. Iterator and its subclasses are usually the structures and methods of the iterators themselves;
Iterable: Iterative, other classes that want to use iterator functionality, such as Abstractlist HashMap. The interface needs to be implemented.

Combination mode Group objects into a tree structure to represent the ' part-overall ' hierarchy. The combined mode makes the user consistent with the use of individual objects and composite objects.

Objects by implementing (inheriting) a uniform interface (abstract class), the caller is consistent with the operation of a single object and a composite object.
By implementing the combined pattern, the caller's action on the combined object is consistent with the operation of the single object.

The caller does not care whether this is a combination object or a file, and does not care about the detailed structure inside the composition object, it can invoke the related method and implement the function.

Observer pattern Defines a one-to-many dependency between objects so that when each object changes state, all objects that depend on it are notified and actively updated themselves.

The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. When the subject object changes in state, all the observer objects are notified so that they can proactively update themselves.

In the Java language Java.util Library, a observable class and a observer interface are provided, which form the Java language support for the Observer pattern.

Façade mode The external communication with a subsystem must be done through a unified façade object.

Advantages of Façade mode:
Loosely coupled
The façade mode is loosely coupled between the client and the subsystem. Make the modules inside the subsystem easier to extend and maintain.
Simple to use
The façade mode makes the subsystem more easy to use, the client no longer needs to understand the internal subsystem of the implementation, nor need to interact with the modules inside many subsystems, just need to interact with the façade class can be.
Better division of the interview hierarchy
By reasonable use of facade. can help us to better classify the level of access. Some methods are external to the system, and some methods are used internally by the system. Concentrate the functions that need to be exposed to the outside in the façade. This makes it easy for the client to use and hides the internal details very well.
Memo Mode Without compromising the encapsulation. captures the internal state of an object. and save this state outside of the object. This allows the object to be restored to its previously saved state. A Memo object is an object that is used to store a snapshot of the internal state of another object.

The purpose of the memo mode is to capture (capture) the state of an object without destroying the package, and to externally and store it so that it can be restored to the stored state at the appropriate time in the future. Memo patterns are often used in conjunction with Command mode and iterative sub-patterns.

Interview mode Encapsulates certain operations that act on elements of a data structure. It is able to define new operations that act on these elements without changing the data structure.
The interview pattern is the behavior pattern of the object. The purpose of the interview pattern is to encapsulate some operations that are applied to a data structure element. Once these operations need to be changed, the data structure that accepts the operation remains intact.
The strengths of the interview model
Good extensibility
The ability to add new functionality to elements in an object structure without altering the elements in the object structure.
Good reusability
The ability to define the entire object structure is common by interviewing people. thereby increasing the degree of reuse.
Detach unrelated behavior
The ability to isolate unrelated behavior by interviewing people. The related behavior is encapsulated together to form an interview person. This allows each of the visitors to have a single function.

Disadvantages of the Interview mode
Object structure changes are very difficult
Does not apply to situations in which classes in an object structure often change. Due to the change in the structure of the object, the interface of the visitors and the realization of the visitors should be changed, and the cost is too high.


Damage encapsulation
The interview pattern usually requires the object structure to open internal data to the visitors and objectstructrue. This destroys the encapsulation of the object.

State mode Agreeing to change the behavior of an object when its internal state changes. This object looks like it has changed its class.
The state pattern agrees that an object changes its behavior when its internal state changes.

This object looks like it has changed its class.

Interpreter mode Given a language, define a representation of his grammar and define an interpreter that uses that representation to interpret sentences in the language.

Enjoy meta mode Reuse objects that already exist in our memory. Reduce the performance consumption of system-created object instances.

Flyweight is the most lightweight in a boxing match. That is, "the level of flies" or "rainfall level", where the use of "enjoy the meta-mode" of the free translation, is because this more reflects the intention of the model. The enjoy meta mode is the structure mode of the object. The enjoy meta mode efficiently supports a large number of fine-grained objects in a shared manner.
The enjoy meta model uses a share to avoid the overhead of having the same content object in large numbers. The most common and intuitive kind of overhead is the loss of memory. The key to sharing the shared meta object is to differentiate between the intrinsic state (the Internal state) and the outer States (External).

Bridge mode Decoupling abstractions and implementations so that they can vary independently.
The bridge model is intended to "decouple abstraction (abstraction) from implementation (implementation) so that they can vary independently".

A very typical example of bridge mode in Java applications is the JDBC drive. JDBC provides a common interface for all relational databases. An application dynamically selects a suitable drive and then sends instructions to the database engine through the drive. This process is to delegate the behavior of the abstract role to the process of implementing the role.


Project

Wrote an Android project embodying 23 design patterns, Project




Test code:

public void Onclicksinglemode (view view) {//singleton singlemode.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) {//Mediator mode intermediarymodel.test1 (); Intermediarymodel.test2 ();} public void Onclickcommandmode (view view) {//Command mode commandmode.test ();} public void Onchainofresponsibilitymodel (view view) {//Responsibility Chain mode Chainofresponsibilitymodel.test ();} public void Onclickdecorativemode (view view) {//Decorate mode decorativemode.test ();} public void OnclicksTrategymode (view view) {//Policy mode strategymode.test ();} public void Onclickiteratormodel (view view) {//mode iteratormodel.test ();} public void Onclickcombinationmode (view view) {//Combo mode combinationmode.test ();} public void Onclickobservermode (view view) {//Viewer mode Observermode.test ();} public void Onclickwindowmode (view view) {//Façade mode windowmode.test ();} public void Onclickmemomode (view view) {//Memo mode Memomode.test ();} public void Onclickvisitormode (view view) {//Caller mode visitormode.test ();} public void Onclickstatemodel (view view) {//state mode Statemodel.test ();} public void Onclickparsermode (view view) {//Interpreter mode Parsermode.test ();} public void Onclickflyweightmode (view view) {//Enjoy meta-mode flyweightmode.test ();} public void Onclickbridgemode (view view) {//bridge mode Bridgemode.test ();}


Summarize

Assume that design patterns are rarely used in coding design careers. The main reason is that the understanding of the design pattern is not enough, the existence of the problem is not recognized.


It is not possible to solve this problem very well because of the inability to correctly analyze and understand the problem.


Project download

Android design mode

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.