Suppose we have different objects to manage, we may create a class to wrap it to manage these different types of objects, such
Class cobjmanager
{
Public:
Bool addobj_a (string const & strobjname, other_params ...);
Bool addobj_ B (string const & strobjname, other_params ...);
.......
Bool updateallobj ();
}
Use the Add function to add the object to the manager. Then, when updating the object, use updateallobj () to update the object data. In this case, update may need to be written in this way.
Bool cobjmanager: updateallobj ()
{
For (I = 0 to num of object)
{
Switch (object. type)
{
Case:
...
Break;
Case B:
...
Break;
...
}
}
}
We can use this manager as follows:
Cobjmanager objmanager;
Objmanager. addobj_a ("this is object a", others ...);
Objmanager. addobj_ B ("this is object B", others ...);
Execute
Objmanager. updateallobj ()
You can.
Do you think cobjmanager: The updateallobj function is too ugly, especially when there are many object types.
The following describes how to use virtual functions to do this, so there is no need for so many switches.
First, define the virtual base class of an object.
Class cobjbase ()
{
Public:
Cobjbase (string const & strobjname );
Virtual bool Update () = 0;
}
Here, uodate is the UPDATE function of the object. For object A, you can write it like this.
Class cobj_a (): Public cobjbase
{
Public:
Cobj_a (string const & strobjname, other_params...): cobjbase (strobjname)
{...}
Virtual bool Update ()
{
...
}
}
Then write an object manager, as shown below:
Class cobjmanager
{
Public:
Bool updateallobj ()
{
For each OBJ
OBJ. Update ();
}
Bool addobj (cobjbase * pobj );
~ Cobjmanager ()
{
For each object
Delete object
}
}
See no. Here, updateallobj does not need to worry about the specific object type. Let C ++ do these tedious tasks!
This object manager can be used in this way.
Cobjmanager objmanager;
Objmanager. addobj (New cobj_a ("this is OBJ a",... other Param ..));
Objmanager. addobj (New cobj_ B ("this is obj B",... other Param ..));
Execute
Objmanager. updateallobj ()
You can.
It looks very convenient to use, but it seems to be a lot more beautiful to write. When you need to add a new type, you only need to add a class...