Java design pattern (i) "Six Principles"

Source: Internet
Author: User

Developing a system is not a difficult thing to do, but why is it that it is a headache to maintain a system? In the author's view, all this comes from the demand. If the requirements are not changed after software development is complete, then most of the programs do not need to be maintained. But, the truth is, demand is changing, and what about us? Also need to embrace these changes. Because of the vagaries of demand, some systems are not designed to be compatible with new requirements. As the demand for these destructive systems becomes more and more, a system slowly becomes difficult to maintain. Is it really impossible to prevent such a thing from happening? Of course not! If we set aside enough space for future changes at the beginning of the design, or that our design begins with a design with good extensibility, flexibility and pluggable features, the system must be compatible with the changes and maintained in accordance with the correct maintenance plan. How to make a good design? The key is to improve the maintainability and reusability of the software appropriately. All right, here's a bunch of crap. The six principles of object-oriented design are now formally introduced I. Opening and closing principle (OCP)Defined: open for extensions, close for modifications. For example: Your class has monitor, study Committee, sports committee and so on a series of class cadres. Because in a collective activity your organization ability is the teacher fancy, want to promote you on duty cadres, but do not want to casually revoke the former cadres, how to do? The monitor proposed to the teacher, he lacks a regiment party secretary, so you are promoted into a regiment party secretary. In this example, the teacher opened a new position-the group secretary, in the expansion of the class cadre at the same time also retained the original team, which is called on the expansion of open, to modify the closure. That is: Do not pass the past to modify the original code logic, to add new features to the system. Of course this is actually a very virtual definition, he only tells you the goal, but does not tell you how to do it. So based on this, the next introduction of the design principles are around the opening and closing principle, tell you how to comply with the OCP second, the Richter substitution principle (LSP)Defined: if each object of type T1 is O1, there is an object O2 of type T2, so that all program P defined in T1 is replaced with O1 for all objects O2, the behavior of program p does not change, then type T2 is a subclass of type T1. A simple generalization is where any parent class appears, and subclasses must be able to appear. For example: There are two horses, the white Horse and the Black Horse, you want to ride a horse, you can riding a black horse, but also can ride the White Horse. Here the horse is the parent class, the White Horse, the Dark Horse is the subclass, you ride the action object is the horse, so as long as you can ride, whether is the white horse or the dark Horse you can ride.
1     classHorse {2         voidRide () {}3     }4     5     classWhitehorseextendsHorse {6         7 @Override8          Public voidRide () {9System.out.println ("Riding a white Horse");Ten         } One     } A      -     classBlackhorseextendsHorse { -          the @Override -          Public voidRide () { -System.out.println ("Ride the Black Horse"); -         } +     } -      +     classMen { A         voidRide (Horse Horse) { at horse.ride ();  -         } -}
Look at the following code:
1     classCalculator {2         voidAddintXinty) {3System.err.println (x+y);4         }5     }6     7     classAdvcalculatorextendsCalculator {8 @Override9         voidAddintXinty) {TenSystem.out.println (x*y); One         } A         voidSubintXinty) { -SYSTEM.OUT.PRINTLN (xy); -         } the}

Subclass Advcalculator overrides the parent class Calculator's Add method, and we can see that when the Add method is called, the expected output is both and, but because the subclass has a copy of the Add method, the result we get when we call the subclass's add is the product of the two, and the expectation is not met.

In fact, this principle hides such a layer of constraint, when Class B inherits the Class A, cannot change the parent class's specification and the restriction (does not arbitrarily rewrite the parent class already to implement the Good method), if the subclass arbitrarily modifies these contracts, then will cause the entire inheritance system to destroy.

* The above principle, in turn, is not true, because the generic class contains new features that the parent class does not have. Iii. Dependency Reversal principle (DIP)Defined: relies on abstraction and does not rely on implementations. For example: Also with the Black horse as an example, Pinkerton riding a white horse to see off, the code is as follows:
1     classWhitehorse {2         3         voidRide () {4System.out.println ("Riding a white Horse");5         }6     }7     8     classMen {9         Ten         voidRide (Whitehorse Horse) { One horse.ride (); A         } -}
But one day, Biaoju no white horse, only dark horse, the Code is as follows:
1     class Blackhorse {2         3         void Ride () {4             System.out.println ("Riding a Black Horse"); 5         }6     }
But now found that Pinkerton incredibly can only ride the White Horse letter, if want to let Pinkerton ride Black Horse letter, it must modify Pinkerton, this obviously has problems, Pinkerton is too capricious, dark Horse is not Ma Yi (coupling too high)? Must let Pinkerton what horse rides, cannot be accustomed to. We introduce an interface to the horse:
    Interface horse{        void  Ride ();    }         class Men {                void  Ride (Horse Horse) {            horse.ride ();        }    }
So the Pinkerton class has a dependency on the interface horse. and the White Horse and the Black Horse have realized the interface horse. This fits the dip and allows our Pinkerton to send all the horses:
1     classWhitehorseImplementsHorse {2         3          Public voidRide () {4System.out.println ("Riding a white Horse");5         }6     }7     8     classBlackhorseImplementsHorse {9         Ten          Public voidRide () { OneSystem.out.println ("Ride the Black Horse"); A         } -}

There is a fact that a good abstraction layer is more solid than the implementation layer. In the author's understanding, abstraction is the process of extracting essential characteristics from concrete objects. It excludes the differences from the same genus before, leaving only a universal common denominator. So a system built on a good abstraction layer is more stable than a system based on a concrete implementation class, and dip is based on it. * Of course, there are some specific classes that may be relatively stable and will not change, and the class that consumes this object can rely entirely on this specific implementation without having to create an abstract class for this Iv. Interface Isolation principle (ISP)Defined: provide the smallest possible interface. For example, an interface is understood as a collection of all the methods provided by a class, that is, a logically existent concept, so that the partitioning of the interface is actually the partitioning of the type. In other words, an interface can be understood as a role, see the following class diagram from the above class diagram can be seen, by an interface a given all the functions, while you can see the class client's next single attribute contains the payment function, while the payment attribute also contains the function of the next order, obviously violates the ISP principle, This is a bad design, so what does it do according to the ISP's approach? As you can see, divide the interface into two roles one payment, one order. Payment is only for the payment, the next single for the order. Do not create a single bloated and huge interface, broken down into roles, a role is only responsible for one thing. v. Synthesis/polymerization multiplexing Principles (CAPP)Defined: reuse objects as much as possible using composition/aggregation, rather than using inheritance. 1. What is composition/aggregation the existing objects are incorporated into the new object and become part of the new object. The difference between composition and aggregation, in fact, is to treat an existing object as a property of a new object. The new object is responsible for managing the life cycle of the synthesized object, such as people and hands, who will be there without a hand?  Aggregation is not, such as companies and employees, the company is no longer, employees of course not with the disappearance of 2, why should try to use synthetic/aggregation A, destroy the package, the implementation details of the superclass are exposed to subclasses. b, the change of the superclass, the change of the subclass C, the inheritance relationship compiler is determined, during operation can not be changed, not flexible enough to give an example: people have multiple identities, such as father, son. If the information is described in an inherited way, it means that the person is either a father or a son. But a man can be both a father and a son. This is obviously unreasonable. The design of this error stems from the mistake of confusing the hierarchical structure of a person with the hierarchical structure of a character. The concept of has-a and is-a is introduced here. Is-a is a strict taxonomic definition, meaning that a class is one of the other classes. And Has-a says that one has a responsibility. Father or son is just a role, a puppy can be a big dog's son, is this puppy has all the characteristics of human behavior? Based on this, the above design is reformed * The Richter replacement principle is the basis of inheritance reuse. Only two classes can be "is-a" when the Richter substitution principle is met. If two classes are "has-a" rather than "is-a" relationships, but are designed to be inherited, then it is definitely against the Richter substitution principle. Vi. Law of Dimitri (LoD)Defined: an object should have as little knowledge of other objects as possibleThere is a simple definition of this rule, don't talk to strangers, just communicate with friends.  So what do you call a friend? 1, this 2, the method into the parameter 3, the object property 4, the object property if it is a collection, all the elements are also friends 5, objects created by the current object any one object satisfies any one of these conditions, is the object friend, the others are strangers. For example, the platoon leader counts how many soldiers he has, code:
1     classPlatoon {2         Privatesquad[] squads;3         4         voidgather () {5             intCount = 0;6              for(Squad squad:squads) {7                  for(Man Man:squad.gather ()) {8Count + =Man.gather ();9                 }Ten             } OneSystem.out.println ("One platoon, one in common" +count+ "soldier"); A         } -     } -      the     classSquad { -        Privateman[] Mans; -         - man[] Gather () { +            return  This. Mans; -        }  +     } A      at     classMan { -         intgather () { -             return1; -         } -}
From the above code can be seen, class platoon design is problematic, platoon directly with the man class occurred communication, so that two classes have been coupled, according to the Lod principle, class only and their friends communicate, man object is obviously platoon strangers. And from the reality of the logic, the platoon leader only need to know that they have a few classes just fine, the class members as long as the squad to the monitor. If hands, it also needs the monitor to do. According to the LOD principle, the improved design is as follows:
1     classPlatoon {2         Privatesquad[] squads;3         4         voidgather () {5             intCount = 0;6              for(Squad squad:squads) {7Count + =Squad.gather ();8             }9System.out.println ("One platoon, one in common" +count+ "soldier");Ten         } One     } A      -     classSquad { -        Privateman[] Mans; the         -        intgather () { -            intCount = 0; -             for(man Man:mans) { +Count + =Man.gather (); -            }  +            returncount; A        }  at     } -      -     classMan { -         intgather () { -             return1; -         } in}

In fact, the Dimitri Law is about the control of the flow of information, the flow of information, and the impact of an object. Hiding the details of the implementation so that the module interacts only with the API, which is actually the hiding of information. It allows modules to be decoupled from each other, allowing modules to be independently developed and maintained for a range of benefits. So it's best to follow the following points when designing a class

1. Prioritize classes to immutable classes

2, try to reduce the access rights of a class

3, minimize the access rights of members

--------------------------------------------------------End--------------------------------------------------------

The above rough introduction of the design pattern of the six principles, is the author's own personal sentiment, if there is a fallacy, welcome to point out. If you are interested in in-depth understanding, you can refer to the Java and mode has other excellent online blog,

Ignition NULL
Source: http://www.cnblogs.com/lightnull/

This article for the ignition null original, welcome reprint, but without consent must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Java design pattern (i) "Six Principles"

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.