Android Custom Component Series "5"--Advanced Practice (1)

Source: Internet
Author: User
Tags iterable

Brief introduction

There are many problems in the process of discovering problems and solving problems in project development, such as repetition, the legacy of some problems, and the essence of these problems is design pattern. Record the knowledge points of design patterns today.

Content

In Java and other object-oriented design patterns, there are 6 main types of relationships between classes and classes: Dependency, association, aggregation, composition, inheritance, implementation. Their coupling degree is increased in turn.

Dependency Relationship:
For two relatively independent objects, when one object is responsible for constructing an instance of another object, or a service that relies on another 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 of Class A. The bidirectional association is represented by the use of Class B as a member variable in Class A, and Class A as a member variable in Class B.
Aggregation relationships:
is a kind of correlation relation, the coupling degree is stronger than the association, their code performance is the same, only is the semantic difference: the Relation object is mutually independent, but the aggregation relation object has the containment relation, between them is "the whole-individual" the interrelationship.
Composition Relationship:
is a stronger coupling relationship. A class that has a composition relationship represents the "whole-part" relationship, and "the whole" is responsible for the life cycle of the "part", and they are symbiotic, and there is no meaning in the "partial" existence alone.
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 Describe
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 class T needs to be modified due to a change in the duty P1 requirements, it is possible to cause a normal function to malfunction P2 functionality.

Solution: Follow a single responsibility principle. Set up two classes T1, T2 respectively, so that T1 complete the functions P1 function, T2 complete functions P2 function. In this way, when the class T1 is modified, the responsibility is not P2 the risk of failure, and similarly, when T2 is modified, the responsibility is not P1 the risk of failure.
The principle of the Richter replacement Definition 1: If for each object of type T1, there is an object O2 of type T2, so that all program P defined by T1 is replaced with O1 for all objects O2, the behavior of program p does not change, then type T2 is a subtype of type T1.
Definition 2: All references to base classes must be able to transparently use objects of their subclasses.
Problem Origin: There is a functional P1, which is done by Class A. Now need to extend the function P1, the function of the extension is P, where p is composed of the original function P1 and the new function P2. The new function p is done by subclass B of Class A, and sub-class B, while completing the new function P2, may cause the original function P1 to fail.

Solution: Follow the Richter substitution principle when using inheritance. When Class B inherits from Class A, try not to rewrite the parent class A's method, but also try not to reload the parent Class A's method, except to add a new method to complete new functionality P2.
Dependency Inversion principle High-level modules should not rely on the lower layers, both should rely on their abstraction; abstractions should not depend on detail; detail should be dependent on abstraction. The problem is that class A is directly dependent on class B, and if you want to change Class A to dependency Class C, you must modify the code of Class A to achieve it. In this scenario, Class A is typically a high-level module that is responsible for complex business logic, and Class B and Class C are low-layer modules that are responsible for basic atomic operations, and if Class A is modified, it poses unnecessary risks to the program.

Solution: Modify 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 modify Class A.
Interface Isolation principle The client should not rely on interfaces it does not need, and the dependency of one class on another should be based on the smallest interface. The problem is that class A relies on class B through interface I, Class C relies on class D through interface I, and if 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.

Solution: Split the bloated interface I into separate interfaces, and Class A and Class C are dependent on the interfaces they need. That is, the principle of interface isolation.
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 another class when one class changes.

Solution: 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 and closed for modification. The problem is: During the software lifecycle, because changes, upgrades, and maintenance are needed to modify the software's original code, errors may be introduced into the old code, or we will have to refactor the entire functionality and require the original code to be re-tested.

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

Design Patterns

The The
Points Defined Describe
Single-Case mode Make sure that there is only one instance of a class, and instantiate it yourself and provide it to the entire system. Single-Case Mode considerations:
You can only use the methods provided by the Singleton class to get the Singleton object, do not use reflection, or you will instantiate a new object. Do not break a dangerous operation that breaks a static reference to a singleton class object with a class. 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, but rather the creation of the work is given to subclasses to do. This core class is transformed into an abstract factory role that is only responsible for giving the interfaces that a specific factory subclass must implement, without touching which class should be instantiated in this detail.
Abstract Factory mode Provides an interface for creating a set of related or interdependent objects without specifying their specific classes. Applies to the Factory method mode in the following cases:
(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 delegates the responsibility of creating an object to one of several helper subclasses, and you want to use which helper subclass is the proxy information localization.
Template method Mode Defines a framework for an algorithm in an operation, and delays some steps into subclasses so that subclasses can 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 cannot 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 "responsibility" thinking. In other words, you should consider which operations must be replaced, which operations can be displaced, and which actions are not replaceable. 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 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 model can enforce a process of construction in stages.
The building pattern is to encapsulate complex internal creation inside, and for external calls, only incoming builders and build tools are needed, and 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 one person or institution acting on behalf of another person or institution. In some cases, a client does not want or cannot refer directly to an object, whereas a 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, by creating a new object from the prototype instance, it is no longer necessary to care about the type of the instance itself, so long as the method of cloning itself is implemented, it is possible to acquire new objects through this method without having to create them through new. The
deeply clones an object in the Java language, often enabling the object to implement the Serializable interface, and then writing the object (which is actually a copy of the object) into a stream (serialized) and then reading it back from the stream (deserializing) to reconstruct the object. Advantages of the

Prototype Mode
Prototype mode allows you to dynamically change the specific implementation type at run time. Prototype mode can be used during the run, by the customer to register the implementation type conforming to the prototype interface, you can also dynamically change the specific implementation type, it seems that the interface has not changed, but actually running is already another class instance. Because cloning a prototype is analogous to instantiating a class. Disadvantages of the

Prototype mode
Prototype mode The main 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 difficult for new classes, and 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, so that the objects do not need to be shown to interact with each other, so that the coupling is loose and the interaction between them can be changed independently. Advantages of the

Broker pattern
Proper use of the mediator pattern avoids over-coupling between colleague classes, making it possible to use the peer classes relatively independently. The
use the mediator pattern to turn a one-to-many association between objects into one-to-one associations, making relationships between objects easy to understand and maintain. The
use the mediator pattern to abstract the behavior and collaboration of objects, and to be able to handle interactions between objects in a more flexible way.
applicable Scenarios
        in object-oriented programming, a class is bound to have dependencies on other classes, and completely independent classes are meaningless. It is also quite common for a class to rely on multiple classes at the same time, since there is a case that a one-to-many dependency has its rationality, and proper use of the mediator pattern can make the original messy object relationship clear, but if abused, it can have a reverse effect. In general, the use of the mediator pattern is only considered if the relationship between the peer class is a network structure. The mesh structure can be transformed into a star-like structure, making the relationship between colleague classes clearer. The
        Broker mode is a more commonly used pattern and a more easily abused pattern. For most cases, the relationship between colleague classes is not complex to a cluttered network structure, so in most cases it is possible to encapsulate the dependencies between objects within a colleague class, and 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, allowing the client to be parameterized using different requests, queuing or logging requests, and supporting revocable operations
Motivation: Separate the "requesting objects" and "the objects receiving and executing these requests".
Common applications:
1. Work queue, thread pool, scheduling
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, which causes the receiver's action to be invoked
4, the caller can accept the command as a parameter, even at run time dynamic
5, the command can support revocation, the practice is to implement an undo () method to return to execute () the state before execution
6, the Macro command is a simple extension of the command, allowing multiple commands to be invoked. The macro method can also support undo
7, the actual operation, it is common to use the "smart" command object, that is, the direct implementation of the request, rather than delegating work to the recipient (the disadvantage?). )
8, the 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 requires a specific handler object to choose only one of two behaviors: one is to take responsibility, but to push the responsibility to the next. A situation in which a specific processor object is not allowed to transmit responsibility after taking part of the responsibility.
In a pure chain of responsibility, a request must be received by a handler object, and in an impure chain of responsibility, a request can eventually not be received by any of the receiving end objects.
The actual example of the pure responsibility chain model is difficult to find, and the examples we see are the implementation of the impure responsibility chain model. Some people think that the impure chain of responsibility is not the responsibility chain at all, which may make sense. But in a real system, a pure chain of responsibility is hard to find. If 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, the decorative mode extends the functionality of the object transparently to the client, and is an alternative to the inheritance relationship. The difference between adornment mode and class inheritance:
1) Decoration mode is a kind of dynamic behavior, random combination of existing classes, and the inheritance of class is a kind of static behavior, what kind of class is defined, what kind of function the object of this class has, can't change dynamically.
2) The decoration mode extends the function of the object, does not need to increase the number of classes, and the class inheritance extension is the function of the class, in the inheritance relationship, if we want to add the function of an object, we can only through the inheritance relationship, in the subclass 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 delegate the invocation of the client to the decorated class, the key to the adornment pattern is that the extension is completely transparent.
Policy mode Define a set of algorithms that encapsulate each algorithm and allow them to be interchanged.
The advantage of the strategy pattern is that you can dynamically change the behavior of the object.
The policy pattern belongs to the object behavior pattern, which is mainly for a set of algorithms, encapsulating each algorithm 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. Typically, a policy pattern is used when an application needs to implement a particular service or feature, and the program is implemented in a variety of ways.
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 slightly different, and it is a mediocre implementation provided to facilitate the creation of a non-mediocre adapter class.
Benefits of Adapter Mode
Better reusability
The system needs to use the existing classes, and the interfaces of this class do not meet the needs of the system. The adapter mode allows for better reuse of these features.
Better extensibility
When implementing the adapter functionality, you can 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, a system if too many occurrences of this situation, is tantamount to a disaster. So if it's not necessary, you can refactor the system without using the 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: Iterators, Iterator and their subclasses are often the structures and methods of the iterators themselves;
Iterable: Iterative, other classes that want to use iterator functionality, such as Abstractlist HashMap, need to implement this interface.
Combination mode Group objects into a tree structure to represent the ' part-whole ' 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 concrete structure inside the composition object, it can call the related method, 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 updated automatically.

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 observer objects are notified so that they can automatically 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 the façade mode:
Loosely coupled
The façade mode is loosely coupled between the client and subsystem, allowing the modules inside the subsystem to be more easily extended and maintained.
Simple to use
The façade mode makes the subsystem more easy to use, the client no longer needs to understand the implementation within the subsystem, and does not need to interact with the modules inside the many subsystems, just interact with the façade class.
Better partitioning of access levels
By using facade wisely, you 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. The ability to expose external functionality to the façade, which makes it easy for clients to use and hide internal details well.
Memo Mode captures the internal state of an object without compromising encapsulation, and saves the state outside that 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 a stored state at the appropriate time in the future. Memo patterns are often used in conjunction with Command mode and iterative sub-patterns.
Visitor mode Encapsulates certain operations that act on elements of a data structure, and it can define new operations that act on these elements without altering the data structure.
The visitor pattern is the behavior pattern of the object. The purpose of the visitor pattern is to encapsulate some operations that are applied to a data structure element. Once these operations need to be modified, the data structure that accepts the operation can remain intact.
Advantages of the visitor pattern
Good extensibility
The ability to add new functionality to elements in an object structure without modifying the elements in the object structure.
Good reusability
You can improve the reusability by defining the functionality common to the entire object structure through the visitor.
Detach unrelated behavior
Visitors can separate unrelated behaviors, encapsulate related behaviors together, and form a visitor, so that each visitor's functionality is relatively single.

Disadvantages of the visitor pattern
Object structure changes are difficult
Does not apply to cases in which the class in the object structure changes frequently, because the structure of the object changes, the interface of the visitor and the realization of the visitor are changed correspondingly, the cost is too high.
Damage encapsulation
Visitor patterns often require an object structure to open internal data to visitors and Objectstructrue, which destroys the encapsulation of objects.
State mode When an object's internal state changes to allow its behavior to change, the object looks like it has changed its class.
State mode allows an object to change 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 Reusing objects that already exist in our memory, reducing the performance consumption of system-created object instances.

Flyweight in boxing is the most lightweight, that is, "The fly level" or "rainfall level", where the choice to use the "enjoy meta-mode" of the free translation, because it is more reflective of 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 mode takes 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 driver. 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) {//Visitor 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

If the design pattern is used very little in the coding design career, the main reason is that the understanding of the design pattern is not enough, the existence of the problem is not recognized.
Because it is not possible to correctly analyze the problem and understand the problem, of course, it is impossible to solve the problem very 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.