The simple factory mode is to encapsulate all kinds of extended function subclasses that inherit the same parent class, and judge the modes of realizing different instantiated objects by passing in different parameters.
Scenario mode: simple logic for implementing a calculator.
1. Write an algorithm class that has two characteristics: there are two numbers to be computed and a result to be returned.
public class Math {
private int numberA;
private int numberB;
public int getNumberA(a) {
return numberA;
}
public void setNumberA(int numberA) {
this.numberA = numberA;
}
public int getNumberB(a) {
return numberB;
}
public void setNumberB(int numberB) {
this.numberB = numberB;
}
public int getResult(a){
return 0; }}Copy the code
2. Algorithmic functions (addition, subtraction, multiplication, division, square root…) will be required. Write it as a subclass of the algorithm. The purpose of doing this is to create an algorithm or modify the internal logic of the algorithm without affecting other algorithm functions. Can achieve high cohesion, low coupling, and extensible.
/ / add
class add extends Math {
@Override
public int getResult(a) {
int numberA = getNumberA();
int numberB = getNumberB();
int result= numberA+numberB;
returnresult; }}/ / subtraction
class sub extends Math {
@Override
public int getResult(a) {
int numberA = getNumberA();
int numberB = getNumberB();
int result= numberA-numberB;
returnresult; }}Copy the code
3. The factory class instantiates objects with different functions according to the parameters of the client. Here the code is set to 0 for addition and 1 for subtraction.
Swith (int) is not supported in JDK1.7
public class Factory {
public Math getMath(int rule) {
Math math=null;
switch (rule) {
case 0:
math = new add();
break;
case 1:
math = new sub();
break;
default:
break;
}
returnmath; }}Copy the code
4. On the client, start computing
public class StartCalculate {
public static void main(String[] args) {
Factory factory = new Factory();
Math math = factory.getMath(1);
math.setNumberA(3);
math.setNumberB(7);
intresult = math.getResult(); System.out.println(result); }}Copy the code
5. Calculation results
-4
Copy the code