The decorator mode of IO stream

Source: Internet
Author: User

Workers

/                      \

Plumber Carpenter

/            \                 /           \

A company Plumber B Company plumber a company Carpenter B Company Carpenter

As shown, if we are to implement the plumber and carpenter of AB, we will implement four classes. To inherit the base class of plumbers and carpenters respectively, if need to add a C company, it is very cumbersome, use

Decorator mode can solve this problem very well, the code of each file is as follows

1.worker.java file

Interface Worker {

public void Dosomework ();

}

2.Plumber. java files

public class Plumber implements worker{
@Override
public void Dosomework () {
System.out.println ("repairing pipes");
}
}

3.Carpenter. java files

public class Carpenter implements worker{
@Override
public void Dosomework () {
SYSTEM.OUT.PRINTLN ("Repairing doors and windows");
}
}

4.ACompany. java files

public class Acompany implements worker{
Private worker worker;
Public Acompany (worker worker) {
This.worker = worker;
}
@Override
public void Dosomework () {
System.out.println ("Hello");
Worker.dosomework ();
}
}

5. Test files

public class Test {

public static void Main (string[] args) {
Plumber worker = new Plumber ();
Acompany aworker = new Acompany (worker);

A plumber works in a company where Aworker is the decorator and theworker is the decorator
Aworker.dosomework ();
Carpenter worker2 = new Carpenter ();
Acompany aWorker2 = new Acompany (WORKER2);

A carpenter working for a company
Aworker2.dosomework ();
}
}

The decorator mode of IO stream

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.