Object-oriented five basic principles (II.) _ Object-oriented

Source: Internet
Author: User
Tags gettext
Objective

Time flies, the teenager is still running ... Ⅰ. The Richter Replacement principle

Brief: On the Richter replacement principle, there may be a use of this principle in every day's code, but it has been used all the time, without realizing that this is the so-called Richter replacement principle. The idea of the Richter substitution principle is: "The functions that can be implemented by the base class can also be implemented by subclasses".

The following code, assuming that there is a list parameter method C, where the logic is based on the index to find the corresponding collection elements, then when you need the list of the Implementation class index lookup function, the list can be implemented Class (ArrayList, LinkedList, etc.) Any one of the parameters as method C passed in, like such code may be encountered every day, but this is the Richter replacement principle embodiment;

Public String C (list<string> contents,int index) {return

        contents.get (index);

    }   

The following code, then assume that there is a method D declared return type is list, can be the following code true return type is ArrayList, and the caller does not know the return type is ArrayList, only know to return the list, this is the Richter replacement principle;

Public list<integer> D () {

        //... Omitting
        //arraylist<integer> ids = new arraylist<integer>;
        return ID;

}

The two examples listed above are the relationships between the interfaces in the collection and the implementation classes, that is, the relationship between the base class and the subclass. The function that the base class can implement, the subclass can replace the base class to implement the corresponding function, this is also the Java object-oriented characteristic embodiment, therefore in the Java language, more really manifests the Richter substitution principle. In fact, in the development of the code, the Richter replacement principle should be everywhere, and then look at the following code, is not the same as the above embodiment;

Main function
  class app{public

        static void Main (String args[]) {

            arraylist<string> str = gethappyneyyear (); C3/>newyearfactory newyearfactory = new Newnewyearfactoryimpl ();
            List<integer> year = newyearfactory.createnewyear (str);
        }

    Demo Interface
    interface newyearfactory{
        list<integer> createnewyear (list<string> strcontent);

    Implement class classes
    Newyearfactoryimpl implements newyearfactory{
        @Override public
        list<integer> Createnewyear (list<string> strcontent) {
            arraylist<integer> year = api.getyear (strContent);
            return year;
        }
   
Summary: The functionality that the base class can implement, subclasses can also be implemented, in inheritance or implementation, subclasses perpetuate the attributes of the base class. Ⅱ. Interface Isolation principle

Brief introduction: The core idea of the interface isolation principle is that the interface should not be too general, and must pursue the specific function.

Suppose the following Hobit interface is provided to the developer to choose a hobby, and just a classmate's hobby is shopping, then a classmate is not going to rewrite the Hobit interface, then implement the Shoppting function logic code.

public interface hobit{

        void Coding ();
        void Readbook ();
        void shopping ();
    }

    public static void Dohobit () {
         Hobit hobit = new Hobit () {
            @Override public
            Void Coding () {

            }
            @Overrid E public
            void Readbook () {

            }
            @Override public
            Void Shopping () {
                //...
            }}
        ;

    }

It is assumed that a classmate's hobby is shopping, can realize Hobit interface when it is also to achieve coding and readbook these two methods, this is not superfluous. Can you remove both of these methods? If remove these two methods, this time just B classmate's hobby is reading, then Hobit interface without Readbook This method, and how to do it.

The above assumption will not feel very contradictory, the interface is too general, will feel redundant code, the interface is too single-minded, that more out of the function and how to achieve it. If you are familiar with Android Click event/Long press Event/touch event for setting controls (such as TextView, button, etc.), you may suddenly realize that the following code, how to set the control click event

Button.setonclicklistener (New View.onclicklistener () {
            @Override public
            void OnClick (View v) {

            }
});
Button.setonlongclicklistener (New View.onlongclicklistener () {
            @Override public
            boolean Onlongclick (View v) {return
                false;
            }
});
Button.setontouchlistener (New View.ontouchlistener () {
            @Override public
            boolean Ontouch View V, Motionevent event) {return
                false;
            }
});

Click event is responsible for the Onclicklistener interface, long by the event by the Onlongclicklistener interface is responsible for touch events by the Ontouchlistener interface, developers to deal with what events, only to implement the corresponding interface. This will not solve the problem of the two problems appearing above, the common cause of code redundancy; Interface specificity leads to a lack of functional problems.

Then take a look at the following on the Android Property animation monitoring interface Implementation, is not that the Android system on the realization of animation monitoring how to violate the principle of interface isolation, the implementation of the animation monitoring interface, but also to rewrite the inside of the four methods, too superfluous it. In fact, it may be that the Android developer was designing this interface, considering that developers might need to use several of these methods at the same time, So it was provided together. Of course, it's also good and bad, and in order to perfect this interface, Android developers have also animatorlisteneradapter another interface, The Animatorlistener method has been implemented empty in this interface, and developers need only rewrite the required methods.

Button button = New button (this);
     Objectanimator animator = objectanimator.offloat (Button, "RotationX", 0, 360);
     Animator.addlistener (New Animator.animatorlistener () {

            @Override public
            void Onanimationstart (animator Animation) {

            }
            @Override public
            void Onanimationend (animator animation) {

            }
            @Override
            The public void Onanimationcancel (animator animation) {

            } @Override the public
            void Onanimationrepeat ( Animator animation) {

            }
});
Summary: In development, should pursue the specific interface, this can avoid a lot of problems; Suppose you wrote the Hobit interface on the first version of the project, and when you had to add the hobby option on a day because of the change in demand, then whether you added the Hobby option to the Hobit interface, This will lead to the project before all the implementation of the Hobit interface must be changed, so the problem ~ ~, so the specificity of the interface can avoid a lot of problems: the above Hobit interface on the hobby, may be listed is not very good, but the general understanding is good. Ⅲ. Dependency inversion principle

In the development of traditional software, typically, an interface or abstract class relies on a specific class, and when a specific class has a change, it has to change its interface or abstract class, and the emergence of the dependency inversion principle is to invert this traditional dependency so that the specific class relies on an interface or abstract class.

Now assume that there is such a demand, the user input information after clicking Submit, the system is responsible for reading, verifying and permanent storage, the following is the Android code implementation:

Findviewbyid (R.id.tv_submit). Setonclicklistener (New View.onclicklistener () {
            @Override public
            void OnClick (View v) {
                String userinput = Medittext.gettext (). toString ();

                if (! Textutils.isempty (userinput) && Inputnews.check (userinput) {   //Verify that the data entered conforms to the business logic
                    sqlitedatabase db = New Dbopenhelper (Provideractivity01.this). Getwritabledatabase ();
                    Contentvalues contentvalues = new Contentvalues ();
                    Contentvalues.put ("Input", userinput);
                    Db.insert ("user", null, contentvalues);
                } else{
                    Toast.maketext (provideractivity01.this, "Sorry, the data you entered is not valid", Toast.length_short). Show ()
                ;

A common phenomenon is that high-level modules rely on the underlying level modules, such as the UI layer in the above code relies on the business layer, and the business layer relies on the data tier. Then how to use the abstraction to realize the dependency inversion principle, solves the above high level module to rely on the bottom module the phenomenon. On the other hand, we do not want a simple complete class to do all the things, then we can think of a single responsibility principle, the various functions are divided to optimize the above code.

Data tier

Public interface DataLayer {
        void Insert (String value);
    }   

    /** Implementation class *
/public class Datalayerimpl implements datalayer{
        private context Mcontext;

        Public Datalayerimpl {
            Mcontext = context;
        }
        @Override public
        void Insert (String value) {
            Sqlitedatabase db = new Dbopenhelper (mcontext). Getwritabledatabase ();

            Contentvalues contentvalues = new Contentvalues ();
            Contentvalues.put ("Input", value);
            Db.insert ("User", null,contentvalues);
        }
    

Business Layer

Public interface Businesslayer {
        void check (String str);
    }

    /** Implementation Class * * Public
class Businesslayerimpl implements Businesslayer {
        private datalayer mdatalayer;
        Public Businesslayerimpl (DataLayer mdatalayer) {
            this.mdatalayer = Mdatalayer;
        }
        @Override public
        void Check (String str) {
            //... Business logic checksum, slightly
            mdatalayer.insert (str);
        }

    

UI Layer

public class Provideractivity extends Appcompatactivity {private EditText medittext;
        Private DataLayer Mdatalayer;

        Private Businesslayer Mbusinesslayer;
            @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
            Setcontentview (R.layout.activity_provider);

            Initview (); Findviewbyid (R.id.tv_submit). Setonclicklistener (New View.onclicklistener () {@Override Pub

                    LIC void OnClick (View v) {String userinput = Medittext.gettext (). toString (); if (!
                        Textutils.isempty (Userinput)) {Mdatalayer = new Datalayerimpl (provideractivity01.this);
                        Mbusinesslayer = new Businesslayerimpl (DataLayer);
                    Mbusinesslayer.check (Userinput); }else{Toast.maketext (Provideractivity01.this, "Sorry, the data you entered is not legal", TOAST.LEngth_short). Show ();

    }
                }
            }); }

Decoupling of data layer and business layer through interface and construction injection; In an object-oriented world, there are several relationships between classes and classes: 0 coupling: There is no coupling between the two classes; Concrete coupling: A direct reference to another class expressed in one class; Abstract coupling: Manifested between a specific class and an abstract class;

The pseudocode above is mainly embodied in abstract coupling, by passing the interface of the data layer to the constructors of the business layer, which makes the dependencies have the greatest flexibility. Finally, our high-level modules are dependent on abstraction (interface). Further, our abstractions do not depend on detail, they also depend on abstraction.
To summarize the above pseudocode, the UI layer is an interface that relies on the business logic layer, and the interface of the business logic layer relies on the interface of the data layer. Summary: Depending on the premise of the use of inverted principle to see the scene, its specific embodiment is in the abstract type, do not abstract to abstract, some relatively stable, remain unchanged classes are not necessary to use. Ⅳ, Summary ... Go on...

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.