Visitor
Post an article with sample code and understanding:
Http://www.cnblogs.com/shanghaif/archive/2008/12/08/1350417.html
I will forward another explanation that I think is the most vivid.
If you want to use an independent object to traverse the tree and call a common method on the tree, you can use iterator. For example, this is an apple tree. You can use a pole to pick up an apple one by one. This is the iterator.
Now you have several trees, such as apple trees, grape trees, and jujube trees. You have different poles for each fruit to extract. In this case, you can use the visitor mode.
Of course, Java objects are all sourced from the ojbect class. Therefore, in principle, all objects come from the same tree and take the object as the root. Assume that a tree has different sub-trees or different fruits on the same tree.
If you do not use the visitor mode, the rows will not work. Then you can use the iterator mode, like this:
While (it. hasnext ()){
Object o = it. Next ();
If (Apple instanceof O ){...}
Else if (grape instanceof O ){...}
...
}
It seems that there is no problem, but once an operation comes in, for example, to create different pesticides for different trees, it is necessary to rewrite this condition for transfer.
After using the visitor model, a miracle has occurred. You put all your poles Into every fruit, and Apple will find its own pole to pick it up, the grape will find the pole to pick the grape and pick it.
If a task such as pesticide or pollination comes in, the visitor mode allows dynamic Addition of a new visitor class to represent pesticide or pollination, so that no code needs to be modified. This is OCP. You put all pesticides in front of each fruit, and the fruit finds the correct pesticide on its own. Put all the pollen in front of the fruit, and the fruit will find the right pollen for its own transmission.
You only have these types of fruit poles, pesticides, and pollen. If you have a new type of fruit, sorry, you have to rewrite the code. The visitor mode does not support OCP in this case.
Template Method
See http://blog.csdn.net/hguisu/article/details/7564039
The parent class is responsible for the logical combination part, implementing the common logical part, and opening the different logical parts of different subclasses through the protected abstract method. The Child class is responsible for specific implementation.
In Android, In the view source code, the draw () method undertakes the logic combination function and is responsible for all the implementation of the drawing logic. At the same time, view also implements a common logical part, such as drawing padding and operating matrix. Different sub-classes are drawn in the form of ondraw, an abstract method.