Design mode (decorative mode)

Source: Internet
Author: User

Decoration mode is used to add properties dynamically and flexibly to an object, consisting mainly of the following roles:

    • Component: defines an object interface that can dynamically add responsibilities to these objects, in this case the product
    • Concretecomponent: The specific object to be added, in this case the Productimpl, the attribute is added by AddAttribute
    • Decorator: The abstraction of the adorner, maintaining a component pointer, and inheriting the pointer; In this case, the Basechange
    • Concretecomponent: Specific adorners, in this case Onechange and Twochange

The code is as follows:

    • Product
 Public Interface Product {    publicvoid  AddAttribute ();}
    • Productimpl
 Public class Implements Product {    @Override    publicvoid  AddAttribute () {        System.out.println ("Add base Attribute");}    }
    • Basechange
 Public class Implements Product {        private  product product;          Public Basechange (product product) {        this. Product= product;    }    @Override    publicvoid  AddAttribute () {        product.addattribute ();    }}
    • Onechange && Twochange
 public  class  onechange extends   Basechange { public  Span style= "color: #000000;" > Onechange (product product) { super   (pro    Duct); } @Override  public  void   AddAttribute () { super  .addattribute ()        ;    SYSTEM.OUT.PRINTLN ( one change ); }}
 Public class extends Basechange {        public  twochange (product product) {        Super(product);    }        @Override      Public void AddAttribute () {        super. AddAttribute ();        System.out.println ("Change");}    }
    • App
 Public class App {    publicstaticvoid  main (string[] args) {        new Productimpl ();                 New Twochange (new  onechange (product));        Change.addattribute ();    }}

The output is:

ADD Base Attributeone changetwo Change

Design mode (decorative 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.