The simple factory pattern should be the simplest and most basic pattern in all design patterns, and here is a simple calculator that uses the Factory mode to write a subtraction.
1, abstract interface class-dependency reversal principle (both upper and lower layers are dependent on abstraction, programming for interfaces)
Class Ioperation{public:ioperation (): m_nnuml (0), M_NNUMR (0) {}virtual~ioperation () {}virtualvoidsetnum (int nNuml = 0, int NNUMR = 0) {m_nnuml = NNUML;M_NNUMR = NNUMR;} Virtualintcalculateresult () = 0;protected:intm_nnuml, m_nnumr;};
Note: M_NNUML, M_NNUMR declared to be protected, is for the inheritance class to be able to use, while maintaining its access to the private, this and C # is not the same place
2, Interface Realization Object Class--addition, subtraction class (multiplication method is omitted, similar)
Class Coperation_add:public Ioperation{public:intcalculateresult () {returnm_nnuml + m_nnumr;}}; Class Coperation_dec:public Ioperation{public:intcalculateresult () {returnm_nnuml-m_nnumr;}};
3. Factory class--Generate abstract objects
<span style= "FONT-SIZE:14PX;" >class cclassfactory{public:cclassfactory () {}~cclassfactory () {}ioperation*createobject (char cOperation) { Ioperation*pocoperation = Null;switch (coperation) {case ' + ': {pocoperation = new Coperation_add (); Case '-': {pocoperation = Newcoperation_dec (); break;} Returnpocoperation;}};
4, the use of factory production objects
Voidtest () {cclassfactoryocclassfactory;ioperation*poioperation = Null;poioperation = OCClassFactory.CreateObject (' + '), if (poioperation) {Poioperation->setnum (2, 3);p rintf ("2 + 3 =%d\n", Poioperation->calculateresult ());d elete Poioperation;}}
The advantage of a simple factory model is that the production process of the specific object is encapsulated, the user does not need to relate to this object how to come, only need just use it, and the object factory this intermediary, can replace the corresponding object according to need, use more flexible. However, in the simple Factory mode, when deciding what object to produce, the switch structure is used, if you need to change or increase or decrease the object, you need to change the code of the switch structure, do not conform to the open-closed principle, that is, functions, classes can not be modified, only extension. How to solve this problem, see tell (Big Talk design mode C + +-table drive method to transform simple Factory mode)
Big talk design mode C + +-Simple Factory mode