本帖最后由 hg3093483 于 2013-4-6 13:02 编辑
近日小弟习得多态,接触到了一种简单工厂模式不甚理解,希望哪位大神不吝赐教。想知道工厂模式的作用,开发当中应该注意的东西有哪些。下面是我的代码。
import java.util.*;
class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个整数");
int a = sc.nextInt();
System.out.println("请输入第一个整数");
int b = sc.nextInt();
Random ra = new Random();
char[] ch = {'+','-','*','/','%'};
char c = ch[ra.nextInt(5)];
Operation op = OperationFactory.getInstance(c);
int result = op.oper(a,b);
System.out.println(""+a+c+b+"="+result);
}
}
class OperationFactory {
public static Operation getInstance(char c) {
Operation op = null;
switch (c) {
case '+':op = new Add();break;
case '-':op = new Sub();break;
case '*':op = new Mul();break;
case '/':op = new Div();break;
case '%':op = new Mod();break;
}
return op;
}
}
class Operation {
int oper(int a,int b) {
return 0;
}
}
class Add extends Operation {
int oper(int a,int b) {
return a+b;
}
}
class Sub extends Operation {
int oper(int a,int b) {
return a-b;
}
}
class Mul extends Operation {
int oper(int a,int b) {
return a*b;
}
}
class Div extends Operation {
int oper(int a,int b) {
return a/b;
}
}
class Mod extends Operation {
int oper(int a,int b) {
return a%b;
}
}
|