79.JAVA Programming Ideas--abstract applications

Source: Internet
Author: User

79.JAVA Programming Ideas--abstract applications

1 Abstract Applications

Next, consider the rest of the design-where to use the class? Since the way the bins are categorized is very indecent and too revealing, why not isolate the process and hide it in a class? This is the famous "If you must do something indecent, at least localize it into a class" rule.


Now, as long as a new type of trash join method, the initialization of the Trashsorter object must be changed. As you can imagine, the Trashsorter class should look like this:

Class Trashsorter extends vector{

void sort (Trash t) {/* ... */}

}

In other words, Trashsorter is a vector (series) of a series of handles that point to a vector of trash handles, and with addelement () you can install the new Trashsorter as follows:

Trashsorter ts = Newtrashsorter ();

Ts.addelement (New Vector ());

But now, sort () has become a problem. How does a statically encoded method cope with the fact that a new type is added? To solve this problem, the type information must be removed from the sort () so that all it needs to do is invoke a generic method that takes care of all the details involved in the processing of the type. This is, of course, another way to describe a dynamic binding method. So sort () simply iterates through the sequence and invokes a dynamic binding method for each vector. Since the task of this method is to collect garbage slices of interest, it is called grab (Trash). The structure now becomes the following:


Where Trashsorter needs to invoke each grab () method, and then, depending on what type the current vector holds, a different result is obtained. In other words, vectors must be aware of the type they hold. The traditional way to solve this problem is to create a basic "Trashbin" class and inherit a new derivative class for each of the different types that you want to accommodate. If Java has a parameterized type mechanism, it may be the most straightforward approach. But for each class that this mechanism should build for us, we should not do cumbersome manual coding, and later the "watch" approach provides a better way to encode.

The basic guideline for OOP design is "to use data members for changes in state, to use polymorphism for changes in behavior." For the vector that holds paper (paper) and the vector that holds the glass (glass), you might initially think that the grab () method used for each of them would certainly have different behavior. But exactly how it all depends on the type, not something else. It can be interpreted as a different state,

And since Java has a class that can represent a type (class), it can be used to determine what type of trash a particular tbin will accommodate.

The builder for Tbin requires that we pass a class of our choice for it. This tells the vector what type it wants to hold. The grab () method then checks with class Bintype and Rtti to see if the trash object we passed to it matches the type it wants to collect. The complete solution is listed below. Numbers that are set to comments (such as *1*) make it easy to compare the instructions listed later in the program.

2 Multi-Dispatch

The above design scheme is certainly satisfactory. The addition of new types within the system involves adding or modifying different classes, but there is no need to make a wide range of changes to the code within the system. In addition, RTTI is not used inappropriately. However, we still have available

Can take a step further and look at the Rtti in the most "pure" perspective, considering how to eliminate it completely in the garbage classification system. To achieve this goal, it is important to realize that for all activities that have special relevance to different types-such as detecting a specific type of garbage and placing it in the appropriate bins-these activities should be controlled through polymorphism and dynamic binding. The previous example was to sort by type and then manipulate a series of elements belonging to a particular type. Now, once you need to manipulate a particular type, stop and think about it. In fact, the whole purpose of polymorphism (dynamically bound method invocation) is to help us manage information that has special relevance to different types. So why do you have to check the type yourself?

The answer lies in the notion that Java only performs a single dispatch. In other words, if an operation is performed on objects of unknown type, Java will only invoke a dynamic binding mechanism for one of those types. This certainly does not solve the problem, so finally have to manually judge certain types, in order to effectively produce their own dynamic binding behavior.

To address this flaw, we need to use the "multiple dispatch" mechanism, which means that a single method call can produce multiple dynamic method calls, which in turn will correctly identify multiple types in one process. To meet this requirement, multiple types of structures need to be manipulated: each dispatch requires a type structure. The following example will operate on two structures: the existing Trash series and a series of bins (Trash Bin)-different garbage or scrap will be placed in these barrels. The second hierarchical structure is not absolutely obvious. In this case, we need to artificially create it to perform multiple dispatches (since this example involves only two dispatches, so called "Double Dispatch").

2.1 Implementation of dual dispatch

Remember that polymorphism can only be represented by method calls, so if you want to make dual dispatch work correctly, you must perform two method calls: one in each structure to determine the type. In the trash structure, a new method called Addtobin () is used, and its parameters are an array of typebin. That method will traverse through the array and try to add itself to the appropriate garbage bin, where the double dispatch takes place.


The newly created hierarchical structure is Typebin, which contains its own method, called Add (), and it is also applied in the form of polymorphism. But pay attention to a new feature: Add () has been "overloaded" processing, can accept different garbage types as parameters. Therefore, one of the key points of the double satisfaction mechanism is that it also involves overloading.

The redesign of the program also poses a problem: the current base class trash must contain a Addtobin () method. One of the most straightforward ways to solve this problem is to copy all the code and modify the underlying class. However, if there is no control over the source code, then there is another way to consider: Place the Addtobin () method inside an interface, keep the trash intact, and inherit the new, special type Aluminum,paper,glass and cardboard. Here we are prepared to take the latter approach.

3 accessor Paradigm

Next, let's consider how to apply a design paradigm with a completely different goal to the garbage collation system. For this paradigm, we no longer care about the optimization when adding new trash to the system. In fact, this paradigm makes the addition of new trash more complex. Suppose we have a basic class structure, it is fixed, it may come from another developer or company, and we have no right to make any changes to that structure. However, we would like to add a new polymorphism method to that structure. This means that we generally have to add something to the interface of the base class. Therefore, the dilemma we are facing now is that we need to add a method to the base class and not change the base class on the other hand. How can we solve this problem?

The Visitor paradigm allows us to extend the interface of a primitive type by creating a separate class structure of type Visitor that will be virtualized for the actions that need to be taken on the base type in the future. The basic type of task is to simply "receive" the accessor and then invoke the accessor's dynamic binding method. It looks like this:

1. More combinations?

There are many other codes here, and there is an obvious "associative" (coupling) relationship between the Trash structure and the visitor structure. However, within the set of classes they represent, there is also a high degree of cohesion: only one thing (Trash describes garbage or scrap, and visitor describes what to do with garbage). As a set of excellent design, this is undoubtedly a good start. In the present case, of course, it is only when we add a new visitor type that we can appreciate its benefits. But when adding new types of trash, it seems to be a bit of a handicap.

The low-level combination of classes and classes and the cohesion within the class are undoubtedly an important design objective. But just a little bit of inattention can prevent us from getting a design that would have been better. On the surface, some classes inevitably have some "intimate" relationships with each other. This kind of relationship usually occurs in pairs, and can be called "couplets" (couplet)-such as collections and Inheritors (enumeration). The front of the trash-visitor seems to be such a "couplet."

is 4 R t i really harmful?

The addition of new types to the system does not affect the code at all, nor does it affect the code in TYPEMAP. This is clearly the most successful solution to the problem. Although it does rely heavily on Rtti, be aware that each key-value pair in the hash table looks for only one type. In addition, when we add a new type, we do not fall into the awkward position of forgetting to add the correct code to the system, because there is no code that needs to be added at all.

5 Summary

On the surface, because the design like Trashvisitor.java contains more code than the earlier design, it leaves a less efficient impression. What we are trying to achieve with various design options should be the focus of our consideration. The design paradigm is particularly suitable for "isolating things that are changing and leaving things intact". and "Things that change" can represent many kinds of change. The change may be due to a program entering a new environment, or because something in the current environment has changed (for example, "the user wants to add a new geometry to the diagram currently displayed on the screen"). Or, as described in this chapter, the change may be an ongoing improvement in the body of the code. Although the previous example of scrap classification emphasized the addition of new trash to the system, Trashvisitor.java allows us to easily add new features without interfering with the trash structure. Trashvisitor.java does have a lot of code in it, but adding new features to the visitor requires minimal cost. If you do this kind of activity often, then more code is worth it.

The discovery of change sequences is not an ordinary matter; Before the initial design of the program, it was impossible for those analysts to predict the change. Unless you enter the late stages of project design, some of the necessary information will not be revealed: sometimes only into the design or the final stage of implementation, you can experience a more in-depth or more difficult to detect their own system needs. When adding a new type (which is the main focus of the "recycling" example), you may realize that you only need a specific inheritance structure when you are in the maintenance phase and you begin to expand your system. Through the design paradigm of learning, you can realize that the most important thing is that the book has been advocating a point of view-polymorphism is OOP (object-oriented programming) of all, has undergone a radical change. In other words, it is difficult to "get" the polymorphism, and once it is obtained, it is necessary to try to sculpt all of your designs into a particular mold.

The point of view of the design paradigm is that "OOP is not just about polymorphism". It should be related to oop that "separates things that are going to change and things that remain the same". Polymorphism is a particularly important means of achieving this goal. And if the programming language directly supports polymorphism, then it is particularly useful (because of direct support, so you do not have to write it yourself, thus saving a lot of effort and time). But the design paradigm reveals to us some other conventional ways of achieving the basic goals. And once you are familiar with and mastered its usage, you will find that you can make more innovative designs.

Because the book "Design Patterns" had such an important impact on programmers, they began to look for other paradigms. As time goes on, such paradigms will inevitably become more and more. Jimcoplien (Http://www.bell-labs.com/~cope home page author) to us

Some of these sites are recommended, with a number of valuable paradigm descriptions:

Http://st-www.cs.uiuc.edu/users/patterns

Http://c2.com/cgi/wiki

Http://c2.com/ppr

Http://www.bell-labs.com/people/cope/Patterns/Process/index.html

Http://www.bell-labs.com/cgi-user/OrgPatterns/OrgPatterns

Http://st-www.cs.uiuc.edu/cgi-bin/wikic/wikic

Http://www.cs.wustl.edu/~schmidt/patterns.html

32T

Http://www.espinc.com/patterns/overview.html

Please also note that an authoritative design paradigm meeting, called Plop, is held every year. A number of academic papers were published and the third session was held at the end of 1997, and all the information was published by Addison-wesley.

79.JAVA Programming Ideas--abstract applications

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.