Lying design pattern ------ simple factory pattern

Factory Method pattern: a factory method pattern defines an interface for creating an object, but let subclasses decide which class to instantiate technology. The method of making a factory to instantiate the class to delay its subclasses.

A simple factory pattern:

Examples of objects are no longer used when the new Object () form, related classes can be instantiated according to the user's choice. For the client, to rely on a specific class of addition. Specific examples described are given only to the plant, the plant will automatically return to a specific instance of an object.

 

 

import lombok.Data;

@Data
public abstract class Operation {

private double numberA = 0;
private double numberB = 0;

public abstract double getResult() throws Exception;
}

public class OperationAdd extends Operation{
@Override
public double getResult() {
return getNumberA() + getNumberB();
}
}
public class OperationSub extends Operation {
@Override
public double getResult() {
return getNumberA() - getNumberB();
}
}
public class OperationMul extends Operation {
@Override
public double getResult() {
return getNumberA() * getNumberB();
}
}
public class OperationDiv extends Operation  {
@Override
public double getResult() throws Exception {
if(getNumberB() == 0){
throw new Exception("除数不能为0");
}
return getNumberA() / getNumberB();
}
}

public class OperationFactory {

public static Operation createOperation(String operate){
Operation operation = null;
switch (operate){
case "+" :
operation = new OperationAdd();
break;
case "-" :
operation = new OperationSub();
break;
case "*" :
operation = new OperationMul();
break;
case "/" :
operation = new OperationDiv();
break;
}
return operation;
}
}

public class TestOperation {

public static void main(String[] args) {
Operation operation = OperationFactory.createOperation("+");
try {
operation.setNumberA(10);
operation.setNumberB(20);
System.out.println(operation.getResult());
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

Guess you like

Origin www.cnblogs.com/zsmcwp/p/11614431.html