Some overviews of Java design patterns

Source: Internet
Author: User

Design patterns have always played an important role in the software industry. Recently feel that their knowledge of design patterns have been forgotten, although I have seen a lot, but frankly speaking, actually did not understand. Basic or to meet the interview. Then, in the work, also rarely use so many design patterns, most of the work is involved in single-case mode, Factory mode or decorative mode. Slowly, I feel that the design pattern seems to be farther away from oneself, become a kind of indefinitely thing. So hurry up and mend your mind. When the brain complements, the feeling of knowledge is really a kind of warm and know something new.

In fact, design patterns represent more of an idea, just like object-oriented. You are in the process of development, also learned to use a lot of design patterns, but you do not know that this is the design pattern of a certain ... Because of this, it can be comfortable and easy to understand if you look at design patterns as a thought rather than as a tool. Since the design pattern is basically geared to the language of OOP, the idea of OOP should be the basis for your reading.

I'd like to drop a few sentences about education here. We have always criticized that our country's education is too rigid and always spoon-fed teaching. I personally think that these really can not count as what is very inferior, then foreign that set is very good. Now, in retrospect, we will find that this is what we call cramming teaching, and there is a good side to it, that is, you always have the foundation of some theoretical knowledge, no matter what. As for the future of personal development, learning and the impact of the work can not be blamed on this way of teaching, but we have given too much education mission and task to let the original dissemination of knowledge of this task becomes so heavy ... The reason, in this, but also hope that the students do not complain about the past ducks, the past of the Ducks have gone, good to catch other birds and beasts ~

The design pattern is mostly biased, and is mainly about the basic 23 modes, and will not discuss derivative design patterns such as MVC, MVP, or other mv*. If you don't know a lot about the basic concepts, it would be better if you went to see some detailed books first. OK, all the crap and water are said to be finished, the following began to enter the dry mode.

The basic design pattern is divided into three types, a total of 23 kinds.

  Create pattern : Factory method mode, abstract Factory mode, creator mode, prototype mode, Singleton mode.

  Structural mode : Appearance mode, adapter mode, proxy mode, decoration mode, bridge mode, combined mode, and enjoy meta mode.

  Behavioral Patterns : Template method mode, observer mode, State mode, strategy mode, responsibility chain mode, Command mode, visitor mode, mediator mode, Memo mode, iterator mode, interpreter mode.

First, the creation pattern--this kind of pattern studies is if the problem that creates an object better

  1, factory method mode (Factory pattern) --Design a specialized factory class Factory, which is used to create some more complex objects (that is, its initialization is more complex, not simply the new Constructor () So simple) as: Bitmap Bitmap = Bitmapfactory.createbitmap (a,b,c);

  2, abstract Factory pattern-This mode is based on the factory method pattern. Design an abstract factory interface, and then implement it to produce specific factory classes to create more complex objects. Abstract Factory method classes are considered when we need factory method classes to solve complex object creation problems and discover that complex objects belong to a series of related objects, that is, when the management of object creation occurs.

  3, Creator pattern (Builder pattern)-when we need to create a complex object, and this complex object before using the assembly is also more complex, like the Android Alertdialog. Then you might consider using the creator mode.

  4, Prototype mode (Prototype pattern)-when we need to dynamically create or load a certain level of objects, these objects are relatively stable outside, the prototype model is more appropriate. Because the prototype pattern implementation is based on the clone of Java, which is to copy an object and then manipulate the copied object directly.

  5, Singleton mode (Singleton pattern)-This mode should be used more than the mode. Because we often run into scenarios where only one instance can be allowed. The most is the print log. But we often find that some of the classes that are actually util types are written in Singleton, which is completely unnecessary.

Second, the structure pattern-the creation pattern solves the problem about object creation. However, when the object is created, it encounters a number of object compositions and the relationship management problem between the object and the object. And this type of problem is the structure of the pattern to be solved.

  1. Appearance mode (facade pattern)-Provides a consistent interface for a set of interfaces in a subsystem, defining a high-level interface. This model realizes the loosely coupling relation between the system, and makes the external interface of the subsystem more concise and easy to use.

  2, Adapter mode (Adapter pattern)--The result of an interface is always fixed, but externally there are always a variety of result requirements. How to get an interface that returns a single result type that satisfies a variety of invocation requirements (which is also based on the original return data of the interface), which is the scenario that the adapter pattern handles, which makes it possible for those classes that would otherwise not work together because of incompatible interfaces.

  3, Proxy pattern--this mode is to strengthen the function of some core classes. A specific operation can be performed after the method of the target object is called. Therefore, in order to implement the proxy mode, there is generally at least one abstract or interface, a realobject and a proxyrealobject, while Proxyrealobject is accompanied by realobject applications, When an interface method is called externally, the proxy class does an operation after calling the real core class.

  4. Decoration mode (Decorator pattern)--dynamically expands the functionality of an object without having to change the original class file and use inheritance. Add some additional responsibilities by creating a wrapper object to wrap the real object. At first glance, it's actually quite like a proxy model. This is possible because the proxy mode can also implement this function. However, we should pay attention to the proxy mode is to implement the interface. And the decorative mode is more to deal with those that do not fit through the generation of subclasses, such as a large number of independent extensions, if to support each combination will produce a large number of subclasses, it will make the number of sub-class explosive growth. Of course there is also a case where the definition of a class is hidden, or it is a final class that cannot be used to generate subclasses.

  5, Bridge mode--some types because of their own logic, it may have multiple dimensions of change, how to deal with this "multi-dimensional change" is the bridge mode to solve the problem. For example, type A has a1,a2,a3, type B also has b1,b2,b3, while the actual type used is a*b*, that is, if the method inherited by tradition will have 3*3=9 independent type. Any one dimension plus 1 or one more dimension changes, then the number of final types will multiply and if the latter changes slightly, maintenance will be very cumbersome, obviously not very reasonable. We try the bridge mode to analyze the problem, we will find that the final type has two dimensions of the change, a * and b* changes are independent is also determined, can not be changed, but the external supply is a*b* is irresistable. We should build a bridge for A and b to make A and b independent and free to mix. This is also the interpretation of the bridge pattern image.

Bridging mode transforms inheritance relationships into associations, reducing the coupling between classes and classes, and reducing the amount of code written. But in its definition it describes the following: "Separating the abstractions from the implementation, so that they can be independently changed." Note that the following abstractions do not refer to the simple interface in Java but the abstract type of A and B, which includes interfaces A and B, as well as a * and b*, while the implementation part refers to the part that is ultimately used externally, that is, the a*b* combination.

6, Combination mode (Composite pattern)--   also known as partial-overall mode, the combined mode allows users to have consistent operations on the use of individual objects and composite objects. The classic image example is a tree-structured file system. In the use of external systems, they can be unified to the directory and files, to delete the increase.

  7, enjoy meta-mode (Flyweight pattern)--This mode is commonly used to reuse the existing objects in our memory, reducing the performance consumption of the system creation object instance. More broadly, the use of shared technology effectively supports a large number of fine-grained objects. If an application uses a large number of similar or even repetitive objects, and these objects cause significant storage overhead, you can consider whether you can use the enjoy meta mode.

Third, the behavior pattern--the object creation and the structure are all handled well, the new question comes again, is the object behavior how to be more reasonable, more effective rate, more coordinated with each component to complete a series of tasks. Behavioral patterns are specifically focused on these issues. Because of the diversity of behavior, it also leads to a lot of schemes in behavioral patterns. To understand the thought behind, we can use it flexibly.

  1, Template method pattern--is to define a template logic to deal with similar logical framework problems of the design pattern. In the object-oriented development process, we encounter a problem: We know the key steps required by an algorithm, and determine the order in which these steps are executed. However, the implementation of some steps is unknown, or the implementation of some steps is related to the specific environment. For example, an abstract class that defines an order of operations, in which a final method Runall calls Run1,run2,run3, and the subclass can redefine some specific steps of the algorithm without changing the structure of an algorithm. The core of the pattern: encapsulating the invariant part, extending the variable part, the behavior is controlled by the parent class, the subclass is implemented, and the public part code is provided for easy maintenance.

  2. Observer mode (Observer pattern)-The target object manages all the observer objects that are dependent on it and proactively notifies when its own state changes. This pattern defines a one-to-many dependency between objects, so that when the state of an object changes, all objects that depend on it are notified and refreshed automatically.

  3. State pattern-This mode is used to solve the state transitions of complex objects in the system and the encapsulation of behaviors in different states. State mode can be considered when there are multiple states for an object in the system, which can be converted between states, and if the objects behave differently in different states. State mode separates the state of an object from the object, encapsulates it into a specialized state class, makes the state of the object flexible, and for the client there is no need to care about the transformation of the State of the object and the current state of the object, regardless of the state of the object, which the client can handle uniformly.

  4. Policy mode (strategy pattern)--The pattern is used in a project where there are several algorithmic policies to choose from, and the client decides to use a specific algorithm strategy at runtime depending on the requirements. In the implementation process, a different algorithm strategy is defined first, and then the client takes the algorithm policy as one of its parameters. such as the Collections.sort () method in Java, which uses the comparator object as a parameter. Depending on the implementation of the comparator interface, the objects are sorted by different methods.

  5. Responsibility chain mode (Chain of Responsibility pattern)-In this mode, many objects are linked together by each object's reference to its next-generation chain. The request is passed on this chain until an object on the chain decides to process the request. The client making this request does not know which object on the chain is ultimately processing the request, which allows the system to reorganize and assign responsibilities dynamically without affecting the client. Just like the TouchEvent event in Android, it is passed down one layer at a level, and if it is processed, it is not passed down.

  6. Command Pattern--This mode encapsulates a request into an object (parameter + behavior), which enables the parameterization of the client's different requests. The general structure is the Command interface, the command* implementation class, receiver receiver (usually a queue). This pattern is a typical pattern for encapsulating behavior, decoupling the contact between the sender and the recipient. The sender invokes an action, and the recipient accepts the request to perform the corresponding action, since the sender does not need to know any interface of the recipient by using Command mode decoupling.

  7. Visitor Mode (Visitor pattern)-encapsulates the operations of elements that act on a data structure, and it can define new operations that act on these elements without changing the data structure. The advantage of the visitor pattern is that it is easy to increase the operation because increasing the operation means adding new visitors. The visitor pattern centralizes the behavior in a visitor object, and its change does not affect the system data structure. The disadvantage is that it is difficult to add new data structures. If the data structure is not very stable, then the visitor mode will not apply.

  8. Mediator Mode (mediator pattern)-This pattern wraps a series of objects interacting in such a way that they do not have to be clearly referenced by each other. So that they can be more loosely coupled. When the interaction between some objects in these objects changes, there is no immediate effect on the interaction between some of the other objects. Thus ensuring that these interactions can vary independently from one another. Typical example-the computer's CPU, monitor, memory, sound card, hard disk, optical drive are connected, there is no need to contact. The motherboard is the equivalent of a mediator. If there is no motherboard, then an object will have to deal with several objects associated with it. And because of the different connections, each object is so, the system referred to as "over-coupled system" ... With the motherboard (mediator), each object to be processed into a single mediator, the mediator knows how to deal with all the accessories, so much easier.

  9. Memo Mode (Memento pattern)--stores and externalities the state of an object without destroying the package, so that it can be restored to storage state at the appropriate time in the future. The implementation is a management class that creates a memo object that is only coupled to the management class. As in the Android system, the state of the activity object is saved.

  10, the iterator pattern (Iterator pattern)-The main process of the collection object, the idea is to provide a way to access the elements of an aggregated object in sequence, without exposing the object's internal structure. This is also the most used mode in Java, the Java Collection class can implement the iterator pattern, the objects inside the collection to traverse. The advantage of the iterator pattern is that it simplifies the traversal of complex collections, encapsulates them well, and users simply need to get iterators to traverse them, while the traversal algorithm does not need to be cared for. But its shortcomings are also obvious, that is not suitable to deal with relatively simple (like arrays or a sequence of tables), using iterators to traverse simple fission rather cumbersome, large as a list, we prefer to use the Foreach loop to traverse.

  11, Interpreter mode (interpreter pattern)-this pattern is the rule that defines the language, and an interpreter is created to explain the semantics of the rule. If a particular type of problem occurs at a sufficiently high frequency, it is worthwhile to describe each instance of the problem as a sentence in a simple language, and you will naturally need to construct an interpreter to interpret the sentences to solve the problem. The interpreter pattern is rarely used in actual system development because it causes problems with efficiency, performance, and maintenance, and it is common practice to use other tools and even languages to accomplish this type of business logic.

  

  Conclusion: Knowledge can never be learned, but if you have a higher level of knowledge rather than rote learning, living with any bit of it will arouse your use of this knowledge.

Some overviews of Java design patterns

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.