zoukankan      html  css  js  c++  java
  • 简单工厂模式

    通过工厂来返回不同的对象,可使用同一种方法。

    抽象类:

    public abstract class Operation {
        private double numA;
        private double numB;
        private double result;
        
        public double getNumA() {
            return numA;
        }
        public void setNumA(double numA) {
            this.numA = numA;
        }
        public double getNumB() {
            return numB;
        }
        public void setNumB(double numB) {
            this.numB = numB;
        }
        public abstract double getResult();
        
    
    }

    加减乘数实现类:

    public class AddOperation extends Operation {
        
        public double getResult() {
            
            return super.getNumA()+super.getNumB();
        }
        
    }
    
    public class SubOperation extends Operation  {
        public double getResult() {
            return super.getNumA()-super.getNumB();
        }
    }
    
    public class MulOperation extends Operation  {
        public double getResult() {
            return super.getNumA()*super.getNumB();
        }
    }
    
    public class DivOperation extends Operation {
        @Override
        public double getResult() {
            return super.getNumA()/super.getNumB();
        }
    }

    工厂类与实现:

    public class OperationFactory {
        public  static  Operation createOperation(String type){
            switch (type) {
            case "+":
                return new AddOperation();
            case "-":
                return new SubOperation();
            case "*":
                return new MulOperation();
            case "/":
                return new DivOperation();
            default:
                break;
            }
            return null;
            
        }
        
        public static void main(String[] args) {
            Operation operation;
            operation=OperationFactory.createOperation("+");
            operation.setNumA(1);
            operation.setNumB(1);
            System.out.println(operation.getResult());
        }
    }

    这样通过控制显示层的代码即可控制整个实现逻辑。。。

  • 相关阅读:
    Leetcode53_Spiral_Matrix
    leetcode 分类
    bash 脚本
    关闭占用端口
    blue bossa
    判断对称二叉树
    This server is in the failed servers list: localhost/127.0.0.1:16000 启动hbase api调用错误
    在cikuapi.com上抓取相关词
    那些天使用AWS填过的坑和注意事项
    一百个人的十年-读后感
  • 原文地址:https://www.cnblogs.com/blackdeng/p/8995247.html
Copyright © 2011-2022 走看看