简单工厂模式

本文以一个简单的计算器为例来说明简单工厂模式:

第一定义一个抽象计算类

/*定义一个抽象计算类
 * 类名:Calculation
 * 属性: numberA,numberB,用于计算的两个操作数。
 * 抽象方法:getResult()
 * */
public abstract class Calculation {


protected double numberA;
protected double numberB;
Calculation(double numberA,double numberB)
{
this.numberA=numberA;
this.numberB=numberB;

}
public abstract  double getResult();


}


第二,定义该抽象类的各个具体子类

public class AddCalculation extends Calculation {
 
/*父类自定义一个构造方法,子类也需要自定义一个构造方法(因为不能在实例化的时候调用默认构造方法)
 * 
 * 
 * */
AddCalculation(double numberA, double numberB) {
super(numberA, numberB);
// TODO Auto-generated constructor stub
}


@Override
public double getResult() {
// TODO Auto-generated method stub
double result=0.0;
result=numberA+numberB;
return result;
}



}


public class DivCalculation extends Calculation{


DivCalculation(double numberA, double numberB) {
super(numberA, numberB);
// TODO Auto-generated constructor stub
}


@Override
public double getResult() {
// TODO Auto-generated method stub
double result=0.0;
if(0!=numberB)
result=numberA/numberB; 
else
{
System.out.println("除数不能为0!!!");
}
return result;
}




}


public class MulCalculation extends Calculation {


MulCalculation(double numberA, double numberB) {
super(numberA, numberB);
// TODO Auto-generated constructor stub
}


@Override
public double getResult() {
// TODO Auto-generated method stub
double result=0.0;
result=numberA*numberB;
return result;
}


}




public class SubCalculation extends Calculation{


SubCalculation(double numberA, double numberB) {
super(numberA, numberB);
// TODO Auto-generated constructor stub
}


@Override
public double getResult() {
// TODO Auto-generated method stub
double result=0.0;
result=numberA-numberB;
return result;
}



}


第三,客户端

public class CalculationFactory {

private static double numberA;
private static double numberB;
public CalculationFactory(double numberA,double numberB)
{
this.numberA=numberA;
this.numberB=numberB;
}
/*方法名:calculationFactory
* 功能:静态工厂方法,通过输入字符+-* /来选择要实现的实例对象。
* 返回值:返回一个父类实例对象Calculation

* */
public static Calculation calculationFactory(char str)
{
Calculation cal=null;
switch(str)
{
case'+':
{
cal=new AddCalculation(numberA,numberB); 
}break;
case'-':
{
cal=new SubCalculation(numberA,numberB);
}break;
case '*':
{
cal=new MulCalculation(numberA,numberB);
}break;
case '/':
{
cal=new DivCalculation(numberA,numberB);
}break;

}
return cal;
}


}



你可能感兴趣的:(java,设计模式)