材料清單:Mobile(手機(jī)),MiniCharger(迷你充電器),IUsb(USB接口),
設(shè)計(jì)思路:
1.聲明IUsb約定對(duì)象之間的交互方式,其中包含一個(gè)事件;
2.Mobile實(shí)現(xiàn)IUsb接口,這是關(guān)鍵點(diǎn),是調(diào)用者實(shí)現(xiàn)接口,需求通過事件委托給充電設(shè)備自行處理;
3.Mobile反射充電設(shè)備,通過構(gòu)造函數(shù)注入IUsb;
代碼清單:
1 public interface IUsb {2 decimal Voltage { get; set; }3 event System.EventHandler Connecting;4 }IUsb.cs
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Mobile.aspx.cs" Inherits="Mobile" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title></title> 9 </head>10 <body>11 <form id="form1" runat="server">12 <div>13 <label>電壓:</label><asp:Label ID="lblVoltage" runat="server" Text="0" ></asp:Label>14 <asp:Label ID="lblMessage" runat="server" Text="沒電了" ></asp:Label>15 <asp:DropDownList ID="drpSelect" runat="server">16 <asp:ListItem Text="迷你充電器" Value="MiniCharger"></asp:ListItem>17 </asp:DropDownList>18 <asp:Button ID="btnConnect" runat="server" Text="連接充電設(shè)備" OnClick="btnConnect_Click" />19 </div>20 </form>21 </body>22 </html>Mobile.aspx
1 using System; 2 public partial class Mobile : System.Web.UI.Page, IUsb { 3 public decimal Voltage { get; set; } 4 public event EventHandler Connecting; 5 PRotected const decimal Increment = 0.5m; 6 protected const decimal Max = 5.0m; 7 8 protected object LoadCharger(string pType) { 9 string _fileName = "Z://" + pType + ".dll";10 object[] _args = new object[] { this };11 return System.Activator.CreateInstanceFrom(12 _fileName, pType, true, 0, null, _args, null, null);13 }14 15 protected void btnConnect_Click(object sender, EventArgs e) {16 this.LoadCharger(this.drpSelect.SelectedItem.Value);17 this.ShowMessage();18 }19 20 protected void ShowMessage() {21 if (this.Connecting == null) this.lblMessage.Text = "設(shè)備無(wú)響應(yīng)";22 else {23 this.Connecting(null, EventArgs.Empty);24 this.lblVoltage.Text = this.Voltage.ToString();25 this.lblMessage.Text = (this.Voltage==0)?"設(shè)備無(wú)充電功能"26 : (this.Voltage == Max) ? "瞬間充滿" 27 :"充電中";28 }29 }30 31 }Mobile.aspx.cs
1 using System; 2 [Serializable] 3 public class MiniCharger { 4 protected IUsb Usb { get; set; } 5 protected const decimal Voltage = 5.0m; 6 public MiniCharger(IUsb pElement) { 7 this.Usb = pElement; 8 this.Usb.Connecting += Element_Connecting; 9 }10 11 void Element_Connecting(object sender, EventArgs e) {12 this.Usb.Voltage = Voltage;13 }14 }MiniCharger.cs
我只是寫個(gè)骨架,有興趣的朋友可以多實(shí)現(xiàn)幾個(gè)不同類型的Usb設(shè)備,并且可以嘗試擴(kuò)展Usb接口的功能,比如說(shuō)為手機(jī)增加拷貝數(shù)據(jù)的功能,
看看連接筆記本電腦和充電器的不同效果
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注