Decorator of Design Pattern-home decoration
Recently I made a house decoration and made a set of furniture, so I went to the market to find the paint master and paint apprentice.
Paint masters mainly buy paint and adjust paint. Paint apprentices mainly paint (team spirit? Haha, it reminds me of CS. You can pick up the dishes first .).
1. Here, we first define the paint job as an interface class:
Public interface work
{
Public void brush (); // paint
}
2. Because the job of paint masters and paint apprentices is to paint, they need to implement the work interface:
A: paint apprentice
Paint paint is mainly done by paint apprentices. Therefore, we define paint apprentices as brusher. (The paint master said, "Do you want to work more .", The paint apprentice whispered, "you have more heads .").
Public class brusher implements work {
Public void brush (){
System. Out. println ("paint ");
}
}
B: paint artist
We define the painter as a decorator.
Public class decorator implements work {
Private work;
// The Painter's work is placed in this list
Private arraylist prework = new arraylist ();
// Paint master's default work
Public decorator (Work work ){
This. Work = work;
Prework. Add ("buy paint ");
Prework. Add ("paint ");
}
Public void brush () {// paint, paint master should also implement this method
Newwork (); // when the paint master receives a job, a new job begins.
}
// New job
Public void newwork (){
Prework (); // The preliminary auxiliary work done by the paint master
Work. Brush (); // Let the apprentice paint the work.
}
// The preliminary auxiliary work done by the paint artist
Public void prework (){
Listiterator = prework. listiterator ();
While (listiterator. hasnext ()){
System. Out. println (string) (listiterator. Next () + "done ");
}
}
3. Compile the test class:
Public class test {
Public static void main (string ARGs []) {
Work bursher = new brusher ();
Work decorator = new decorator (bursher );
Decorator. Brush ();
// I will hand over my work to the paint master, and then assign the paint master the practical work to the paint apprentice.
}
4. Description:
A: The code is only used to learn the decorator mode. To run the code, you must make some changes.
B: In this process, I only deal with the paint master. The specific paint is between the paint master and the paint apprentice. I don't have to worry about it.
C: the reason for using decorator is that these functions need to be dynamically determined by the user. decorator provides the "plug-and-play" method to determine when to add a function during running.