一:利用抽象工厂建造一个加减乘除运算器:
下面是具体的代码实现:
Cal抽象方法:
package com.hbc.factory; public abstract class Cal { public abstract int getResult(int a, int b); }
Add:
package com.hbc.factory; public class Add extends Cal{ @Override public int getResult(int a, int b) { return a + b; } }
Sub:
package com.hbc.factory; public class Sub extends Cal{ @Override public int getResult(int a, int b) { return a - b; } }
Mul:
package com.hbc.factory; public class Mul extends Cal{ @Override public int getResult(int a, int b) { return a * b; } }
Div:
package com.hbc.factory; public class Div extends Cal{ @Override public int getResult(int a, int b) { return a / b; } }
Operation:这个类是具体操作,以及测试:
package com.hbc.factory; import java.util.Scanner; public class Operation{ public static Cal getCal(char c){ Cal cal = null; switch(c){ case ‘+‘: cal = new Add(); break; case ‘-‘: cal = new Sub(); break; case ‘*‘: cal = new Mul(); break; case ‘/‘: cal = new Div(); break; default: System.out.println("不好意思,您输入的操作有误"); } return cal; } public static void main(String[] args) { System.out.println("请输入您要进行的操作"); Scanner cin = new Scanner(System.in); while(cin.hasNext()){ String op = cin.next(); Cal cal = getCal(op.charAt(0)); System.out.println("请输入您要操作的数字"); int a = cin.nextInt(); int b = cin.nextInt(); System.out.println("计算的结果是: " + cal.getResult(a, b)); System.out.println("请输入您要进行的操作"); } } }
时间: 2024-10-13 09:07:09