the benefits of abstract factory patterns
Originally in writing a design pattern of the experience of the article, but this week busy tutorial compiling principles, first write a little bit of it.
In advance, the following content is my personal experience, not guaranteed to be correct, comprehensive and reasonable.
--------
In the number of GOF, the creation pattern has several, the most common is the factory method, simple description:
You need to create many objects, such as rectangles, circles, rounded rectangles (maybe this is a configuration software, or Visio).
You can come to new anywhere, but people with a little experience will choose to be responsible for creating objects in a specific way. Such as:
cdrawobj* createdrawobj (int ObjType)
The benefits of doing so are obvious:
1. The code is concentrated.
2. If you modify the Createdrawobj function, you can not affect the external code. For example, Crectdrawobj was thought to have a problem, someone wrote a new
Class Crectdrawobjex, that as long as the modification of createdrawobj, you can be unknown to replace.
The above example, assuming we understand the concept of virtual function, CDrawObj is such a virtual base class. (C # is more willing to abstract as interface)
OK, now the code situation is:
There is a createdrawobj function, and then other places are strewn with calls to this function.
If I had a whole new set of drawobj now, and wanted to switch between the two sets of drawobj at the moment of operation.
It is intuitive to add a parameter to Createdrawobj: cdrawobj* createdrawobj (int objtype,int Category)
In fact, this method is also very good.
But Oo does not like this set, we like to encapsulate the variables inside the object, so the above function becomes two:
cfactory* createfactory (int factorytype)
Cfactory::createdrawobj (int ObjType)
In this way, when we want the whole Drawobj family to be replaced, it's just a different factory in Createfactory,
All other places do not need to be modified. Instead of using cdrawobj* createdrawobj (int objtype,int Category), in each call
Createdrawobj, you should pass in different category parameters according to the situation.
Encapsulating variables into objects is a small trick of object-oriented design.
I don't know if I have made myself clear.
To be honest, the abstract factory is not a lot of places to use, more common is the factory method template method combination, which is more commonly used in the framework design.