Java design pattern-decorator mode

Source: Internet
Author: User

Defined:

The ability to dynamically extend an object without having to change the original class file and use inheritance. It is by creating a wrapper object, that is, decorating to wrap the real object.

Overview:

1. The decorator and the decorated object have the same super-type.

2. You can wrap an object with one or more decorators.

3. Since the decorator and the decorated object have the same super-type, in any case where the original object (wrapped) is needed, it can be replaced with a decorated object.

4. The decorator may, before and/or after the act entrusted to the decorator, add his or her actions to achieve a specific purpose.

5. Objects can be decorated at any time, so you can decorate objects dynamically and without limits at runtime with your favorite decorators.

Design principle: 1. Multi-use combination, less inheritance.

The behavior of using inheritance design subclasses is statically determined at compile time, and all subclasses inherit the same behavior. However, if you can extend the behavior of an object with a combination of practices, you can dynamically extend it at run time.

2. Classes should be designed to be open to extensions and closed for modification. Example: Use the configuration coffee drink to do the example

For example, there is now a beverage class (beverage) that adds different ingredients to the beverage (steamed milk (steamed Milk), soy milk (Soy),
Mocha (Mocha, which is chocolate flavor) or covered with milk foam), will be formulated a variety of different kinds of drinks, the price also varies with the added ingredient, the beverage store needs to calculate the price, if the specific subclass inherits the beverage class and takes into account all combinations, will be a "class explosion":

What is more disgusting is that if the price of a certain ingredient changes, it must contain this ingredient corresponding to the implementation of some beverage subclasses, remember: The class should be open to the extension and closed for modification.
Apply decorator mode, just like the object to wear the same layer of a layer will expand dynamic add up, flexible elastic

Examples used in Java: IO design

Bufferedinputstream and Linenumberinputstream all extend from FilterInputStream, while FilterInputStream is an abstract decoration class.

Features of decoration mode

1) decorative objects and real objects have the same interface. This allows the client object to interact with the adornment object in the same way as the real object.

2) Adornment object contains a reference to a real object (reference)

3) The Adornment object accepts all requests from the client. It forwards these requests to the real object.

4) Decorative objects can add additional functionality before or after forwarding these requests. This ensures that additional functionality can be added externally without modifying the structure of a given object at run time. In object-oriented design, the extension of functionality to a given class is usually achieved through inheritance.

Applicability
    1. You need to extend the functionality of a class or add additional responsibilities to a class.

    2. It is necessary to dynamically add functionality to an object, which can then be withdrawn dynamically.

    3. It is necessary to increase the number of functions produced by the permutation of some basic functions, thus making the inheritance relationship impractical.

    4. When a method of generating subclasses cannot be used for expansion. One scenario is that there may be a large number of independent extensions that will produce a large number of subclasses to support each combination, resulting in an explosive increase in the number of subclasses. Another situation may be because the class definition is hidden, or the class definition cannot be used to generate subclasses.

Advantages
    1. The purpose of the decorator pattern and the inheritance relationship is to extend the functionality of the object, but decorator can provide more flexibility than inheritance.

    2. By using different decorative classes and the arrangement of these decorations, designers can create a combination of many different behaviors.

Disadvantages
    1. This is more flexible than inheritance, but it also means more complexity.

    2. Adornment mode causes many small classes to appear in the design, which can complicate the program if overused.

    3. The adornment mode is programmed for the abstract component (Component) type. However, if you are programming for a specific component, you should rethink your application architecture and whether the decorator is appropriate. Of course, you can change the component interface, add new public behavior, and realize the "translucent" decorator pattern. Make the best choice in the actual project.

Mode simplification
    1. If there is only one concrete Component class and no abstract Component interface, you can let decorator inherit concrete Component.

    2. If there is only one concrete decorator class, you can merge decorator and concrete decorator.

The difference between a decorator and an adaptive model

1. About new responsibilities: Adapters can also add new responsibilities at the time of conversion, but the primary purpose is not here. The decorator mode is mainly for the decorator to add new responsibilities.

2. About the original interface: The adapter mode is to use the new interface to invoke the original interface, the original interface to the new system is not visible or unavailable. The decorator mode uses the original interface intact, and the object that is decorated by the system is also used through the original interface. (The adorner mode that adds a new interface can be thought of as its variant – "Translucent" decorator)

3. About the object of its package: The adapter is aware of the details of the person being adapted (that is, that class or that interface). The decorator knows only what its interface is, and whether its specific type (base class or other derived class) is known only during run time.

Specific examples:

The various roles in the adornment mode are:
(1) abstract component (Component) role: An abstract interface is given to standardize the objects that are ready to receive additional responsibilities.
  
(2) Specific component (concrete Component) Role: Defines a class that will receive additional responsibilities.
  
(3) decoration (Decorator) Role: Holds an instance of a component (Component) object and implements an interface that is consistent with the abstract component interface.
  
(4) Specific decoration (concrete Decorator) role: Responsible for adding additional responsibilities to the component objects.

In the following example, Thirdparty.java is assumed to be an existing or third-party feature, for some reason we cannot modify it directly, it provides a saymsg () method, and what we want to do now is to add something we want to output in its saymsg () method, So we rewrote a Decorator.java class. Mailtest.java is a client-side test program.

ithirdparty.java--Abstract Interface Class ===================== PackageDECORATOR.SAYSTR; Public  interface ithirdparty { PublicStringsaymsg();} thirdparty.java--Specific Class =================== Public  class thirdparty implements ithirdparty { PublicStringsaymsg() {return "Hello"; }}decorator1.java Concrete Decoration Class1================== PackageDECORATOR.SAYSTR; Public  class Decorator1 implements ithirdparty {PrivateIthirdparty ThirdParty; Public Decorator1(Ithirdparty thirdparty) { This. thirdparty= ThirdParty;} PublicStringsaymsg(){return "# #1"+ thirdparty.saymsg () +"# #1";}} Decorator1.java Concrete Decoration Class2================== PackageDECORATOR.SAYSTR; Public  class Decorator2 implements ithirdparty {PrivateIthirdparty ThirdParty; Public Decorator2(Ithirdparty thirdparty) { This. thirdparty= ThirdParty;} PublicStringsaymsg(){return "# #2"+ thirdparty.saymsg () +"# #2";}} mailtest.java==================== PackageDECORATOR.SAYSTR; Public  class mailtest { Public Static void Main(string[] args) {Ithirdparty Thirdpartyone =NewThirdParty (); Ithirdparty Decorator1 =NewDecorator1 (Thirdpartyone); Ithirdparty Decorator2 =NewDecorator2 (Decorator1); System.out.println (Decorator2.saymsg ());}}
My QR code is as follows, welcome to exchange discussion

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference:
"Head First design mode"
Http://baike.baidu.com/view/2787758.htm
http://yulingtianxia.com/blog/2014/05/10/zhuang-shi-zhe-mo-shi/

Java design pattern-decorator mode

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.