([Article title] Improve calculator code with simple factory pattern structure - "reflection" technique
【Programming Environment】JDK1.6.0_01
[Author's Statement] Looking forward to forwarding the article, but please keep the integrity of the article and indicate the source of the article.
The first chapter in "Ghost Talk Design Patterns" is an example of a simple calculator built with a simple factory pattern. On pages P10-P11 of the book, there is a factory class, OperaationFactory, which is used to structure instances of various operation classes. The contents are as follows:
//Enter the operator symbol, the factory instantiates the appropriate target, and realizes the effect of the calculator by returning to the parent class through polymorphism
publicclassOperaationFactory
{
publicstaticOperationcreateOperate(stringoperate)
//pass in the operation type selected by the requirement
{
Operationoper=null;
switch(operate)
{
case :
oper=newOperationAdd();
break;
case-:
oper=newOperationSub();
break;
case
:
oper=newOperationMul();
break;
case/:
oper=newOperationDiv();
break;
}
returnopr;
}
}
But here is a problem: if you need to add a new operation class, in addition to repairing the interface code, you also need to add a new sentence to the switch of the OperationFactory!!! Its effective "reflection" can solve this problem well (note that : The book "Ghost Talk Design Patterns" is C# code, and the code repaired in this article is implemented in java, please pay attention to the difference in implementation between the two).
The "reflection" technology can map each component of the class into a target. Using the "reflection" technology, the incoming string can be used as a parameter to create an instance target of the class. Briefly explain the two functions required:
(1)forName()
staticClasslt;?gt;forName(StringclassName)
className: class name
Return value: class target of className
(2) newInstance()
Effect: Creates an instance of the class with the class's target
The code of the factory class OperaationFactory rewritten in java is as follows:
////Enter the operator symbol, the factory instantiates the appropriate target, and realizes the effect of the calculator by returning to the parent class through polymorphism.
classOperaationFactory
{
//The class name of the operation class of the incoming requirement structure
publicOperationcreateOperate(stringoperatstring)
{
Operator=null;
//Get the class target of the operation class
ClaSSCla=Class.forName(operatstring);
//Get the instance target of the operation class, and the return type is Object
Objectobj=cla.newInstance();
//Force type conversion
oper=(Operat)obj;
returnoper;
}
}
The following is the code after repairing in java:
//Abstract class for algorithm
abstractclassOperat
{
protecteddoublenumberA=0.0;
protecteddoublenumberB=0.0;
//Set the value of the two numbers to participate in the addition operation
publicvoidsetNumber(doublenumberA,doublenumberB)
{
this.numberA=numberA;
this.numberB=numberB;
}
//Get the result of the operation
publicabstractdoublegetResult();
}
//Addition, detailed algorithm class, abstract class Operat inherited from algorithm
classOperAddextendsOperat
{
//Get the result of the operation
publicdoublegetResult()
{
returnnumberA numberB;
}
}
//Subtraction, detailed algorithm class, abstract class Operat inherited from algorithm
classOperSubextendsOperat
{
//Get the result of the operation
publicdoublegetResult()
{
returnnumberA-numberB;
}
}
//below is the test code
classTest
{
publicstaticvoidmain(Stringargs) throwsException
{
System.out.println(Please enter the operation type:);
//Pass in the operation type that needs to be performed, it must be the class name
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
Stringopsel=br.readLine();
//Create an instance of the factory class
OperaationFactoryopfactory=newOperaationFactory();
/ / Access the method of the child class through the parent class
Operatop=opfactory.createOperate(opsel);
System.out.print(1st number of input operation:);
BufferedReaderbr1=newBufferedReader(newInputStreamReader(System.in));
doublenumberA=Double.parseDouble(br.readLine());
System.out.print(2nd number of input operation:);
BufferedReaderbr2=newBufferedReader(newInputStreamReader(System.in));
doublenumberB=Double.parseDouble(br.readLine());
//Set the value of the two numbers to participate in the addition operation
op.setNumber(numberA,numberB);
// output result
System.out.println(result is: op.getResult());
}
}
The results of the program operation are shown in Figure 1:
123123
figure 1
The red box ① part is generally passed in as a parameter through interface programming, and the user does not need to know which class the addition corresponds to. The pseudocode of interface programming is as follows:
Switch (the operation type selected by the user)
{
Case "Addition":
The input parameters are: OperAdd
Break;
Case "Subtraction":
The input parameters are: OperSub
Break;
}
Let's understand the benefits of "reflection" through a new requirement. Suppose we want to add a multiplication operation, we only need to do the following steps:
1.
Add a multiplication class to inherit the Operat class, and the code is defined as follows:
//Multiplication, detailed algorithm class, abstract class Operat inherited from algorithm
classOperMulextendsOperat
{
//Get the result of the operation
publicdoublegetResult()
{
returnnumberA
numberB;
}
}
2.
Then put the compiled bytecode file in the working directory, as shown in Figure 2:
123124
figure 2
3.
Run the program, as shown in Figure 3:
123125
image 3
We can see that we need to add a function of calculating multiplication to the program, we only need to write a multiplication class alone, and the logic code written before does not need to be changed or changed (of course, the interface code needs to be repaired and the multiplication option is added) . Through the use of "reflection" technology, the "strong cohesion, weak coupling" and "development closure criteria" in target-oriented are more and more exerted.
chat\.classpath
chat\.mymetadata
chat\.project
Improve calculator code with simple factory pattern structure - "reflection" technique\1.gif
Improve calculator code with simple factory pattern structure - "reflection" technique\2.jpg
Improve calculator code with simple factory pattern structure - "reflection" technique\3.gif
Improve calculator code with simple factory pattern structure - "reflection" technology\Oper.java
Improving Calculator Code Using Simple Factory Pattern Structure - "Reflection" Technique\Improving Calculator Code Using Simple Factory Pattern Structure - "Reflection" Technique.doc
.....)