首页 > 代码库 > 设计模式之工厂模式
设计模式之工厂模式
软件开发中为啥需要设计模式?以下四幅画足以说明设计模式的重要性:
那么工厂模式说的是什么呢,解决了什么问题呢:
其实工厂模式解决的是到底实例化谁,将来会不会增加实例化的对象,比如以下例子中需要增加一个开方的运算等,这是很容易变化的地方,应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂,根据条件创造出不同的实例来处理不同的业务。
源码如下:
package gongchang_designmode;
public class FactoryMian {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Operation oper;
oper=(new FactoryMian()).new OperationFactory().createOperate("+");
oper.set_numberA(1);
oper.set_numberB(2);
double result=oper.getResult();
System.out.print(result);
}
/// <summary>
/// 运算类
/// </summary>
public class Operation
{
public double get_numberA() {
return _numberA;
}
public void set_numberA(double _numberA) {
this._numberA = _numberA;
}
public double get_numberB() {
return _numberB;
}
public void set_numberB(double _numberB) {
this._numberB = _numberB;
}
private double _numberA = 0;
private double _numberB = 0;
/// <summary>
/// 得到运算结果
/// </summary>
/// <returns></returns>
public double getResult()
{
double result = 0;
return result;
}
}
/// <summary>
/// 加法类
/// </summary>
class OperationAdd extends Operation
{
public double getResult()
{
double result = 0;
result = get_numberA() + get_numberB();
return result;
}
}
/// <summary>
/// 减法类
/// </summary>
class OperationSub extends Operation
{
public double getResult()
{
double result = 0;
result = get_numberA() - get_numberB();
return result;
}
}
/// <summary>
/// 乘法类
/// </summary>
class OperationMul extends Operation
{
public double getResult()
{
double result = 0;
result = get_numberA() * get_numberB();
return result;
}
}
/// <summary>
/// 除法类
/// </summary>
class OperationDiv extends Operation
{
public double getResult()
{
double result = 0;
if (get_numberB()==0)
try {
throw new Exception("除数不能为0。");
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
result = get_numberA() / get_numberB();
return result;
}
}
/// <summary>
/// 运算类工厂
/// </summary>
class OperationFactory
{
public Operation createOperate(String operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
}
}
}
UML类图:
设计模式之工厂模式