工厂模式(初学)

工厂模式

1、简单工厂模式

  • 是一种创建型设计模式,旨在通过一个工厂类(简单工厂)来封装对象的实例化过程

运算类

  • public class Operation {   //这个是父类
    	private double num1;  //运算器中的两个值
    	private double num2;
    	public double getNum1() {
    		return num1;
    	}
    	public void setNum1(double num1) {
    		this.num1 = num1;
    	}
    	public double getNum2() {
    		return num2;
    	}
    	public void setNum2(double num2) {
    		this.num2 = num2;
    	}
    	
    	public double getResult() {  //用于子类获取结果
    		double result = 0;
    		return result;
    	}
    }
    

加减乘类

  • public class OperationAdd extends Operation{  //加法
    
    	@Override
    	public double getResult() {
    		double result = 0;
    		result = super.getNum1() + super.getNum2();  //从父类获取值
    		return result;
    	}
    }
    
  • public class OperationSub extends Operation{ //减法
    
    	@Override
    	public double getResult() { 
    		double result = 0;
    		result = super.getNum1() - super.getNum2();  //从父类获取值
    		return result;
    	}  
    }
    
  • public class OperationMul extends Operation{//乘法
    
    	@Override
    	public double getResult() {
    		double result = 0;
    		result = super.getNum1() * super.getNum2();  //从父类获取值
    		return result;
    	}  
    }
    

工厂类

  • public class OperationFactory {
    	
    	public static Operation createOperation(String operate) {    //这个是个工厂类
    		
    		Operation op = null;   //这个为null是因为要通过符号来确定子类对象
    		switch (operate) {     //判断符号,实例合适的对象
    		case "+":
    			op = new OperationAdd();
    			break;
    		case "-":
    			op = new OperationSub();
    			break;
    		case "*":
    			op = new OperationMul();
    			break;
    		}
    		return op;
    	}
    }
    

Main

  • public class Main {
    	public static void main(String[] args) {
    		Operation op = new OperationAdd();
    		op = OperationFactory.createOperation("*");   //只要输出合适的计算符号,工厂类就会实例出该有的对象
    		op.setNum1(1);
    		op.setNum2(2);
    		double rusult = op.getResult();
    		System.out.println(rusult);
    	}
    }
    

2、工厂模式实现

你可能感兴趣的:(java,开发语言)