标签:style class java com get string
一个简单的计算器例子来描述工厂模式
Operator公共接口
package com.iss.factory;
public interface Operator {
public int getResult(int x, int y);
}
Add.java
package com.iss.factory;
public class Add implements Operator{
@Override
public int getResult(int x, int y) {
// TODO Auto-generated method stub
return x+y;
}
}
Minus.java
package com.iss.factory;
public class Minus implements Operator{
@Override
public int getResult(int x, int y) {
// TODO Auto-generated method stub
return x-y;
}
}
Mul.java
package com.iss.factory;
public class Mul implements Operator{
@Override
public int getResult(int x, int y) {
// TODO Auto-generated method stub
return x*y;
}
}
Divide.java
package com.iss.factory;
public class Divide implements Operator {
@Override
public int getResult(int x, int y) {
// TODO Auto-generated method stub
return x/y;
}
}
OperatorFactory.class
package com.iss.factory;
public class OperatorFactory {
private static Operator operator = null;
public static Operator getOperator(String op) {
if (op == "+") {
operator = new Add();
} else if (op == "-") {
operator = new Minus();
} else if (op == "*") {
operator = new Mul();
} else if (op == "/") {
operator = new Divide();
} else {
return null;
}
return operator;
}
}
Test.java
package com.iss.factory;
public class Test {
public static void main(String[] args) {
Operator operator = OperatorFactory.getOperator("+");
System.out.println(operator.getResult(10, 20));
}
}
总结:工厂模式其实主要利用了面向对象的多态这个特性。程序在实际运行时会有多个选择状态!
标签:style class java com get string
原文地址:http://blog.csdn.net/wangdianyong/article/details/34837455