[Java design mode] decoration Mode

Source: Internet
Author: User

1. Background

The decoration mode adds a new function to an object and modifies it based on the object. The function implemented in This article is that object a has a way to show and output "This is a test". After decoration, It outputs "This is a test for decorate ". Essentially, multiple classes use one interface, and the class to be modified is defined in the constructor of the modifier class.

2. Code Implementation

(1) first, create a common interface with the show () method ()

 

package Decorate;public interface Component {    public void show();}

 

(2) create a class to implement show

 

package Decorate;public class Concrete implements Component{    public void show(){        System.out.print(This is a test);    }}

(3) create the decorate implementation class

 

 

package Decorate;public class Decorate implements Component {    Component component;    public Decorate(Component c){        component=c;    }    public void show(){        component.show();        System.out.print( for decorate);    }}

(4) Client usage

 

 

package Decorate;public class Client {    public static void main(String[] args){        Component a=new Concrete();        Component b=new Decorate(a);        a.show();        System.out.println();        b.show();    }}

Result

 

 

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.