The research of decorator pattern and code extensibility

Source: Internet
Author: User

  The enhanced optimization and extension of code is the snag of every programmer, and of course the idea and belief we pursue, while decorator mode is an excellent code optimization concept,

Here to share with you some of your own learning experience:

--------------------------------------------------------------------------------------------------------------- ----------------------

  To give a simple example,

 Public Static void action (animal ann) {        ann.figeht ();    }

  Now we want to create an action method, but we don't know who is going to do it, whether the cat is a dog or us, so here we don't say it's written dead,

Instead, it pulls up a animal interface.

 Package test;  Public Interface Animal {    publicvoid  figeht ();      Public void sleep ();}

This is a simple interface-oriented programming idea, and this time we pass the animal interface as a formal parameter into this method. But when we call this method we can't just pass in the animal object, because the interface is not instantiated, so we're going to create a class to implement the animal interface.

 Public class Implements Animal {    @Override    publicvoid  figeht () {        System.out.println (" The cat can beat the little Snake ");    @Override    publicvoid  sleep () {        //  TODO auto-generated method Stub        System.out.println ("Sleeping Animals");}    }

For example, now we create a class of cat classes to implement this interface, and this is how we can call this method

Action (new Cat ()); The cat can beat the little snake.

Here we are passed in a cat class object, of course, we can also pass in the dog, human and so on, and so on, this also greatly improved the code extensibility, can meet our changing needs, this is polymorphic to improve code extensibility typical case; but now we are not satisfied with it, We feel the cat's ability is not strong enough, we want to strengthen the ability of the cat, how to do it? There are two ways of doing this.

The first is inheritance: inheritance is one of the three main features of Java object-oriented programming, I believe everyone is very familiar with, here bloggers will not repeat, but one point to note that the subclass can not inherit the parent class constructor, if the parent class is a walk of the structure, the child class is required to complete the construction of the parent class to initialize Can be used in this way when we can control the construction of the parent class, but it is not recommended when the parent class is too complex for us to know how to construct the parent class.

And the second way is our main character today, but also the blogger's preferred way---decorator mode

We use the Decorator mode to enhance the function of the class, first we need to meet two conditions:

1. The same interface as the enhanced class implementation;

2. An instance object of the enhanced class is constructed by constructing an incoming decorated class;

The code is as follows:

 Public classSupercatImplementsAnimal {//Here we pass a constructor method to pass in a class object to be strengthened first    Privatecat Cat; Supercat (cat c) { This. cat =C; } @Override Public voidfigeht () {cat.figeht (); //Add the features we want to enhance here directlySystem.out.println ("I'm a mongoose, I can torture the cobra."); } @Override Public voidsleep () {//classes that do not need to be reinforced need to be called just by passing in the object as they are, so that we retain the original method and strengthen the//the way we want to strengthenCat.sleep (); }}

This time we call the action method again

// now we think the cat's combat effectiveness is not strong enough, we have to strengthen the effectiveness of the cat, where we use the decorator mode        Action (new supercat (new Cat ()));

// The cat can beat the little snake . // I'm a mongoose, I can torture a cobra.

This time we will get enhanced output, this is a simple demonstration of decorator mode

--------------------------------------------------------------------------------------------------------------- ----------------------------

Finally, let's summarize the similarities and differences between the two ways of enhancement:

Inherited way: Know the parent class constructor is the premise, this way the child parent class produces the relationship, does not conform to the low-coupling, high cohesion programming idea, but the code implementation is simpler

Decorator mode: First to meet two conditions: 1. Implement the same interface as the enhanced class; 2. An instance object of the enhanced class is constructed by constructing an incoming decorated class, in which case the class does not have a relationship with the class and the coupling is low

And we do not need to know the specific creation of the enhanced class object, as long as the object of the enhanced class can be obtained, in line with the low-coupling, high cohesion programming concept, but the code implementation is relatively complex

--------------------------------------------------------------------------------------------------------------- -----------------------------

This kind of low-level design idea, you may feel that the usual use is not much, but we can see this design method in Java API (such as IO stream) and many third-party jar (C3P0 in the connection enhancement) package is widely used, So I hope you can use this code optimization method more

--------------------------------------------------------------------------------------------------------------- -----------------------------

Bloggers feel that the program is to be lazy, bo is a lazy man, so bloggers love programming, since it is to lazy, we will be the most lazy, the same code absolutely does not appear two times, can once and for all, is because of laziness so we pursue the ultimate optimization of code, together to do a perfectionist programmer!!!

The research of decorator pattern and code extensibility

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.