Vistor design pattern

xiaoxiao2021-03-06  94

From C 's point of view, there are several codes to be ugly:

There are too many if else, more, if else judges the class references that come back in the cycle jump, which is common in the MFC. For example: cstatusbar & statusbar = (CMAINFRAME *) (AFXGetApp () -> m_pmainwnd) -> getStatusbar ();

There is a pointer in C, C has a template and inheritance. If you don't need a pointer, you must use an array or index. If you don't understand inheritance, Copy Paste can pass. In fact, don't ask too much, no big deal. True ugly places have no way, have to start from a small place. If you are more LP, TEX is more than the LP, we are not alive.

Turning back, saying Visitor. Andrew Fitzgibbon said that Visitor mode can be designed enough to design the price. Visitor is in order to replace the following code: void f (objectclass & o) {if (Dynamic_cas (& o) / * do one think * / else if (Dynamic_Cast (& O)) / * Do Another Thing * /} It is essentially a wretched person, so before, if I don't allow me to play Dynamic_CAS, I will set an ObjectClass to get a structure, then Define or Const a type of Typenumber. This allows if IF Typenumber = = Object1 ..... else .....

Gamma will be angry.

If you can change the source code of ObjectClass, use inheritance, toss a virture function: p.dosomething () If you don't want to change the source code of ObjectClass, with Visitor.

Specific steps:

1 defines a class of the original visitor class objectVisitorClassclass objectVisitorClass {public: virtual void Visit (objectClass &) = 0; virtual void Visit (objectClass1 &); virtual void Visit (objectClass2 &); virtual void Visit (objectClass3 &);};

2 Add a virtual function in Object Virtual Void ObjectClass (1, 2) :: Acceptvisitor (ObjectvisitorClass & V) {v.visit (* this);

In this way, even if you don't have a rights Object class, you can also change the functionality of the Acceptvisitor function by changing the ObjectVisitorClass.

If so, I think there is no exaggeration that Andrew said. Design a class that is not small, this technology is more gorgeous, but what is the use?

--- to be continued

转载请注明原文地址:https://www.9cbs.com/read-124975.html

New Post(0)