设计模式:简单工厂(Simple Factory)
定义:根据提供的数据或参数返回几种可能类中的一种。
示例:实现计算器功能,要求输入两个数和运算符号,得到结果。
结构图:
HTML:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Simple Factory Demo</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtNumA" runat="server" Width="50px"></asp:TextBox> <asp:DropDownList ID="ddlOperateType" runat="server"> <asp:ListItem Selected="True">+</asp:ListItem> <asp:ListItem>-</asp:ListItem> <asp:ListItem>*</asp:ListItem> <asp:ListItem>/</asp:ListItem> </asp:DropDownList> <asp:TextBox ID="txtNumB" runat="server" Width="50px"></asp:TextBox> <asp:Button ID="btnGetResult" runat="server" Text="=" OnClick="btnGetResult_Click" /> <asp:TextBox ID="txtResult" runat="server" Width="50px"></asp:TextBox> <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label> </div> </form> </body> </html>
运算类:
/// <summary> /// Operation 运算类 /// </summary> public class Operation { public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { return 0; }
减加乘除类:
/// <summary> /// 加法类 /// </summary> public class OperateAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } /// <summary> /// 减法类 /// </summary> public class OperateSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } /// <summary> /// 乘法类 /// </summary> public class OperateMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } /// <summary> /// 除法类 /// </summary> public class OperateDiv : Operation { public override double GetResult() { double result = 0; if (NumberB == 0) throw new Exception("被除数不能为0"); result = NumberA / NumberB; return result; } }
简单工厂类:
/// <summary> /// 简单运算工厂类 /// </summary> public class OperationFactory { public static Operation CreateOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperateAdd(); break; case "-": oper = new OperateSub(); break; case "*": oper = new OperateMul(); break; default: oper = new OperateDiv(); break; } return oper; } }
客户端调用:
protected void btnGetResult_Click(object sender, EventArgs e) { lblMessage.Text = ""; try { Operation opeation; opeation = OperationFactory.CreateOperate(ddlOperateType.SelectedValue); opeation.NumberA = Convert.ToDouble(txtNumA.Text); opeation.NumberB = Convert.ToDouble(txtNumB.Text); double result = opeation.GetResult(); txtResult.Text = result.ToString(); } catch (Exception ex) { lblMessage.Text = ex.Message; } }