A small design for yourself 4-the principle of universal principle of object design

Source: Internet
Author: User

In addition to the core principles of the previous study, there are some derivative principles to master them, and you will be better oriented towards the object. Call them "extension principles". Dimitri rule: Try not to have sex with unrelated classes. The Dimitri Law of Demeter, or Lod, is also known as the least knowledge principle (Least knowledge principle,lkp). There is no fixed definition of this principle, and there are generally several statements:
1 just talk to your friends. 2 . Don't talk to strangers. 3. Objects should only communicate with objects that must interact

In layman's parlance, a class should know the least about the class that it needs to call, how the inside of the class you call is implemented, and I don't care, that's your thing, I know you provide the interface method, I call so much, the other is not concerned about.

It can also be said, do not let the class also infected with the mysterious ambiguous relationship between people.  The simpler the connection between objects, the easier it is to manage. Specifically, technically, the object is required to communicate only with the following types of objects that must interact:
(1) The current object itself(this), (2) The object passed into the current object method as a parameter, (3) The member object of the current object;  4) If the member object of the current object is a collection, the elements in the collection can also be interactive, and (5) The object created by the current object.

In addition, you need to set the object's access rights appropriately.

There are too many positive textbooks, just look at some negative examples:
// method Chaining, which is common in web page development, but does not seem to be recommended in static languages  Public void Do () {  m_accessor. GetUser (). Rename ();} // a meaningless public approach class  publicvoid do () {  workhelper ();}    Public void Workhelper () {}}

Hollywood rule: Don't call me, let me call you. In front of our analysis of the interaction between objects, direct invocation refers to the method of direct invocation of the object, an important part of the indirect call is the callback, especially in asynchronous programming, the Hollywood law is to some extent, is equivalent to at the right time, more use of callback function. The following is the C # version of the event implementation:
 Public classprogram{Static voidMain (string[] args) {User User=NewUser (); View UI=NewView (user); User. Name="Hello"; }} Delegate voidOnnamechange (stringname);classview{ PublicView (user user) {user.onnamechanged+=user_onnamechanged;} voidUser_onnamechanged (stringname) {Console.WriteLine (name);}} classuser{Private stringM_name; Public stringName {Get{returnM_name;} Set{m_name=value;  Onnamechanged (M_name); } }  Public Eventonnamechange onnamechanged;}

This is also the interaction between the MV in the simple MVC pattern, view as the receiver of the event, only need to provide a good callback function, when the model part changes, the view automatically receive changes to update the UI (here just print out).

If the event is not used here (Observer mode), then the model is bound to save the reference to the view (in fact, of course, it still holds the relevant reference, but the observer reasonably uses various abstract methods to arrange the reference management, such as the use of delegate in this example, as C # Relatively weak coupling relationship, it is far more than the direct use of inheritance, to achieve the coupling of the interface is much weaker, when the model data changes, the direct call to view the relevant methods to update the UI, this strong interdependence of the program is not a good practice.  And once a number of uncertain roles like view are interested in changing the model, direct application is often difficult to handle. The movie often says that the single-line connection is the safest, so is also. preferential use of the composition principle: use more combinations, less inheritanceIn addition to inheriting this strong constraint method, the combination of this weakly coupled relationship is more flexible. Look at a small example:
classuser{ Public Virtual voidPrinttype () {}}classadmin:user{ Public Override voidPrinttype () {Console.WriteLine ("Employer"); }}classprogrammer:user{ Public Override voidPrinttype () {Console.WriteLine ("Employer"); }}classmanager:user{ Public Override voidPrinttype () {Console.WriteLine ("Employer"); }}classcontractor:user{ Public Override voidPrinttype () {Console.WriteLine ("Temp"); }}

The company's system in addition to Contractor is almost full of formal employees, printing type only need to print employer, and only contractor need to print temp.

For this function, if we design a class hierarchy like above, the work is perfectly normal. And when there is a new formal employee type, it is only necessary to copy the admin Printtype method, there is no violation of any of the basic or core principles we have described earlier. But we still find the uncomfortable place, that is printing the official staff of the code copied everywhere, what to do? Still is the old routines, the abstraction, the encapsulation, and the passing in.
 Public classprogram{Static voidMain (string[] args) {User Admin=NewAdmin (Newemployerprintor ()); Admin.  Printtype (); User Contractor=NewContractor (Newtempprintor ()); Contractor. Printtype (); }} classuser{printor m_printor; PublicUser (Printor printor) {m_printor=Printor;}  Public Virtual voidPrinttype () {m_printor. Printtype (); }}classadmin:user{ PublicAdmin (Printor printor):Base(Printor) {}}classcontractor:user{ Publiccontractor (Printor printor):Base(Printor) {}}classprintor{ Public Virtual voidPrinttype () {}}classemployerprintor:printor{ Public Override voidPrinttype () {Console.WriteLine ("Employer"); }}classtempprintor:printor{ Public Override voidPrinttype () {Console.WriteLine ("Temp"); }}

For this principle, I would rather describe myself as: rational use of inheritance and combination . As the two most basic means of reusing and describing object relationships, I would like to say that it is appropriate to use inheritance when using scenarios, and to use combinations when using combinations.

Personal Opinion: inherited usage scenarios: satisfies strict is-a relationships, which means that inheritance is necessary when the base class is really a strong constraint for a subclass, that is, when the subclass completely re-uses all the information of the base class. Note that this sentence "strict" and "strong constraint", inheritance as one of the most heavy reuse relationship, use inheritance to consider more, because modern language is a single inheritance (only one Class), multi-implementation (can implement multiple interfaces) of the use of, once the inheritance relationship from the class is used, Extensibility is actually limited to the range of the base class. But once you're sure you need it, put aside your concerns and use it directly. In fact, in all of the previous examples, we are inseparable from inheritance in almost every case. Combined usage scenario: satisfies the relaxed has-a relationship, which means that if a class is just a dependency of another class, it can be used together. Note that this sentence in the "loose", the combination of use can be so "wayward."   For a lot of functions, in fact, pure inheritance can be achieved, but always imperfect, either have redundant members, or the degree of reuse is not enough, this time basically the simple inheritance is not enough, you can try to use "Combination + inheritance" way. Okay, so much for the big rules to get on the stage.

A small design for yourself 4-the principle of universal principle of object design

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.