<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">其实呢?</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">我现在,以我目前的水准来学习这个设计模式,也是合适的。</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">如果是以前,我的代码量根本没到那么一个程度,学学习起来,也肯定没有现在这么容易~</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">
</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近开始学习设计模式这一块的内容,</span>
今天先开始工厂模式:
对于一个计算器,
比较简单,为了写代码,直接翻译需求,是什么样子呢?
是这样:
if( operation == "+" )
return a + b;
else if( operation == "-" )
return a - b;
else if( operation == "*" )
return a * b;
else if( operation == "/" )
return a / b;
而如果,让代码直接,简洁一点,是什么样呢?
是这个样子:
switch(operation){
case "+" :
c = a + b;
break;
case "-" :
c = a - b;
break;
case "*" :
c = a * b;
break;
case "/" :
c = a / b;
break;
}
这样并没有带来,更多的好处,
再来看下一处代码:
public class Operation{
private int _number_A;
private int _number_B;
public int Number_A{
get{
return this._number_A;
}
set{
this._number_A = value;
}
}
public int Number_B{
get{
return this._number_B;
}
set{
this._number_B = value;
}
}
public abstract int GetResult(){}
}
public class OperationAdd : Operation{
public override int GetResult(){
return this.Number_A + this.Number_B;
}
}
public class OperationSub : Operation{
public override int GetResult(){
return this.Number_A - this.Number_B;
}
}
public class OperationMul : Operation{
public override int GetResult(){
return this.Number_A * this.Number_B;
}
}
public class OperationDiv : Operation{
public override int GetResult(){
return this.Number_A / this.Number_B;
}
}
public class Real{
public void Main(){
Operation op = null;
switch(operation){
case "+" :
op = new OperationAdd();
break;
case "-" :
op = new OperationSub();
break;
case "*" :
op = new OperationMul();
break;
case "/" :
op = new OperationDiv();
break;
}
op.Number_A = 1;
op.Number_B = 2;
op.GetResult();
}
}
OK、大概简单的工场模式就到这里吧