I recently started to look at the design model. I think about what I should have known when I was in college. Now I only know what I think ~~~
This is an example of a calculator. Now I want to create a calculator that includes addition, subtraction, multiplication, division, and so on;
Consider designing this class. The general idea is to directly design an operation class that contains the interfaces for addition, subtraction, multiplication, division, and so on.
But is that true? What if we want to add another multiplication operator? Write directly in the operation class? This obviously violates the design's principle of opening and closing. And think about it again.
Think, this design class, Coupling Degree think of high, if you want to change a certain calculation method, you must open the calculation class again, it is estimated that the boss is angry.
Therefore, we consider a simple engineering mode to separate the specific classes and implementations. The structure is as follows:
In this way, if we want to add new operations, we only need to add new computing classes before registering new products in the factory;
Code implementation:
// Computing base class
# Include <iostream>
# Ifndef operation
# Define operation
Class operation
{
Public:
Virtual double getresult (double NUMA, double numb );
Protected:
PRIVATE:
};
# Endif
# Include "operation. H"
// Addition class
# Ifndef operationadd
# Define operationadd
Class operationadd: Public operation
{
Public:
Double getresult (double NUMA, double numb );
Protected:
PRIVATE:
};
# Endif
// Factory
# Ifndef simplefactory
# Define simplefactory
Class simplefactory
{
Public: Operation * creatoperation (char operate );
};
# Endif
// Factory implementation
Operation * simplefactory: creatoperation (char operate)
{
Operation * operator = NULL;
Switch (operate)
{
Case '+': Operator = new operationadd;
Break;
Case '-': Operator = new operationsub;
Break;
Case '*': Operator = new operationmul;
Break;
Case '/': Operator = new operationdiv;
Break;
Default: Operator = new operationadd;
Break;
}
Return response;
}
Client
Int main (void)
{
Double NUMA = 20;
Double numb = 13;
Operation * operator = NULL;
Simplefactory simfac;
Operator = simfac. creatoperation ('/');
Double result = numeric-> getresult (NUMA, numb );
STD: cout <"NUMA/numb's result is:" <result <STD: Endl;
System ("pause ");
Return 0;
}
Note:
/*
* Advantages: it complies with four object-oriented principles: Maintenance, reusability, scalability, high flexibility, and low coupling.
* Disadvantage: to add new products, the factory must be modified, which violates the principle of software design.
*/