码迷,mamicode.com
首页 > 其他好文 > 详细

浅谈工厂模式

时间:2014-06-27 08:34:28      阅读:243      评论:0      收藏:0      [点我收藏+]

标签: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));
}


}

总结:工厂模式其实主要利用了面向对象的多态这个特性。程序在实际运行时会有多个选择状态!





浅谈工厂模式,布布扣,bubuko.com

浅谈工厂模式

标签:style   class   java   com   get   string   

原文地址:http://blog.csdn.net/wangdianyong/article/details/34837455

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!