20. Decorative design mode

Source: Internet
Author: User

1. Decoration Design Pattern Introduction definition

Add some extra responsibilities to an object dynamically. For added functionality, the adornment mode is more flexible than generating subclasses.

2. Decorative design Pattern Usage scenarios

Add some extra responsibilities to an object dynamically.

3. Decorative design mode UML class diagram

Role Description:
    • Component: An abstract component that acts as the original object that is being decorated.
    • Concretecomponent: A component-specific implementation class.
    • Decotor: Abstract Decoration Class: The responsibility is to decorate the Component object, which has a reference to the Component object inside.
    • Concretedecoratora: The concrete implementation class of decorators
    • Client: Test class
4. Decorative design mode Simple implementation
    • (1), first define an abstract component class:
publicabstractclass Component {    /**     * 抽象的方法     */    publicabstractvoidoperation();}

There is only one abstract method in the abstract Component class operation ()

    • (2), component specific implementation class:
publicclass ConcreteComponent extends Component {    @Override    publicvoidoperation() {    }}

Component implementation class inherits self-assembled abstract class, and there are concrete implementation logic in the Operation method.

    • (3), abstract decorator:
publicclass Decorator extends Component {    private Component component;//持有一个component对象的引用    publicDecorator(Component component) {        this.component = component;    }    @Override    publicvoidoperation() {        component.operation();    }}

The abstract decorator class also inherits from the component class, which receives a reference to the Component object of the component type in the constructor, and calls component's Operation method inside the operation () method.

    • (4), Decorator implementation class:
      Concretedecoratora and Concretedecoratorb are just the way the operation method calls the parent class operation method.
 Public  class concretedecoratora extends Decorator {     Public Concretedecoratora(Component Component) {Super(component); }@Override     Public void Operation() {Opetatea ();Super. Operation ();    Opetateb (); }Private void Opetateb() {    }Private void Opetatea() {    }}

The decorator implements the class inside, inherits from the decorator class, inside the operation method calls the parent class operation method, also can carry on the related logic operation itself.

    • (5) Test class:
 Public classClient { Public Static void Main(string[] args) {//Construction of decorated component objectsConcretecomponent concretecomponent =NewConcretecomponent ();//Construct decorator object A, and callConcretedecoratora Concretedecoratora =NewConcretedecoratora (concretecomponent);        Concretedecoratora.operation (); System. out. println ("----");//Construct decorator object B, and callConcretedecoratora Concretedecoratorb =NewConcretedecoratora (concretecomponent);    Concretedecoratorb.operation (); }}

In order to get a better understanding of decorator design patterns, there are now the following scenarios:

For example, we are going to buy a fried rice, if nothing added, as long as five yuan, add green pepper, more than five yuan, add shredded pork words more charge.

    • (1), Rice base class:
publicabstractclass Rice {    private String name;    publicgetName() {        return name;    }    publicabstractintgetPrice();}

Rice base class There is a name and a price:

    • (2), fried Rice base class:
publicclass FryRice extends Rice {    publicFryRice() {    }    @Override    publicgetName() {        return"炒饭";    }    @Override    publicintgetPrice() {        return5;    }}

Fried Rice The return price is 5 yuan

    • (3), batching class, equivalent to the above decoration class
public   class  ingredient  extends  rice     { private  Rice; public  ingredient  (rice)    {this . Rice = rice; }  @Override  public  String getname  () {return  rice.getname (); }  @Override  public  int  getprice  () {return  Ric    E.getprice (); }}
    • (4), Ham ingredients
 Public  class Ham extends ingredient {     Public Ham(rice) {Super(rice); }@Override     PublicStringGetName() {return Super. GetName () +", add Ham."; }@Override     Public int GetPrice() {return Super. GetPrice () +3; }}
    • (5), lean meat Ingredients:
 Public  class Lean extends ingredient {     Public Lean(rice) {Super(rice); }@Override     PublicStringGetName() {return Super. GetName () +", add lean meat"; }@Override     Public int GetPrice() {return Super. GetPrice () +4; }}
    • (6), test class:
 Public classClient { Public Static void Main(string[] args) {//Fried Rice base classFryrice Fryrice =NewFryrice (); System. out. println (Fryrice.getname () +","+ Fryrice.getprice ());//lean meat Fried Rice base classLean Leanfryrice =NewLean (Fryrice); System. out. println (Leanfryrice.getname () +","+ Leanfryrice.getprice ());//Lean ham Fried RiceHam ham =NewHam (Leanfryrice); System. out. println (Ham.getname () +","+ Ham.getprice ()); }}

The test results are as follows:

    炒饭,5    炒饭,加瘦肉,9    炒饭,加瘦肉,加火腿,12
5. Decorative design mode in the Android source code

In Android, we often use the startactivity () method to start a component in activity.

StartActivity This method was first defined in the context, which is an abstract class that defines many abstract methods. The context is equivalent to the abstract component within the decorative design pattern .

The startactivity implementation is done in Contextimpl. Contextimpl is equivalent to a specific implementation of a component.

Activity inherits from Contextthemewrapper,contextwrapper and inherits from context.

In Contextwrapper there is the following code:

Context mBase;publicContextWrapperbase) {    base;}@OverridepublicvoidstartActivity(Intent intent) {    mBase.startActivity(intent);}

It can be seen that the contextwrapper is our decorator.

Finally, give a few classes of relationships:

6. Summary
    • Advantages:
      • The purpose of adornment mode and inheritance is to extend the function of the object, but the adornment mode can provide more flexibility than inheritance. The inheritance relationship is static and is determined before the system is run; the decorative design pattern allows dynamic decision to add or remove these "decorations".
      • The combination of different decorative classes and the arrangement of these decorations can create many different combinations of behaviors.
    • Disadvantages:
      • Generate redundant classes.

20. Decorative design 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.