Zero丨丶小余

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  13 随笔 :: 0 文章 :: 0 评论 :: 7681 阅读

目的:通过继承操作类,将单个操作分离出来,前端通过工厂类获取实现对象。
用到:继承、多态、封装
factory-》operation-》getResult()

前端通过调用工厂类获取具体实现对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;
 
public class main {
 
    //实现计算器的功能,输入2个数字和1个运算符号
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        double numOne = sc.nextDouble();
        sc = new Scanner(System.in);
        String operate = sc.nextLine();
        sc = new Scanner(System.in);
        double numTwo = sc.nextDouble();
        operation operation = operationFactory.createOperation(operate);
        operation.setNumA(numOne);
        operation.setNumB(numTwo);
        double result = operation.getResult();
        System.out.println(result);
    }
}

  写一个工厂类,获取具体对象,这里也可以通过反射获取具体对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class operationFactory {
 
    public static operation createOperation(String operate){
        operation oper = null;
        switch (operate){
            case "+":
                oper = new operationAdd();
                break;
            case "-":
                oper = new operationSub();
                break;
        }
        return oper;
    }
}

  具体实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class operation {
 
    private double numA = 0;
    private double numB = 0;
 
    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 double getResult(){
        double result = 0;
        return result;
    }
}

 具体实现,重写getResult()方法

1
2
3
4
5
6
7
public class operationAdd extends operation {
 
    @Override
    public double getResult(){
        return getNumA()+getNumB();
    }
}

  

1
2
3
4
5
6
7
8
Connected to the target VM, address: '127.0.0.1:39957', transport: 'socket'
5
+
4
9.0
Disconnected from the target VM, address: '127.0.0.1:39957', transport: 'socket'
 
Process finished with exit code 0

  

posted on   Zero丨丶小余  阅读(264)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 聊一聊 操作系统蓝屏 c0000102 的故障分析
阅读排行:
· DeepSeek V3 两周使用总结
· 回顾我的软件开发经历(1)
· C#使用yield关键字提升迭代性能与效率
· 低成本高可用方案!Linux系统下SQL Server数据库镜像配置全流程详解
· 4. 使用sql查询excel内容
点击右上角即可分享
微信分享提示