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