材料清單:Mobile(手機),MiniCharger(迷你充電器),IUsb(USB接口),html
設計思路:ide
1.聲明IUsb約定對象之間的交互方式,其中包含一個事件;函數
2.Mobile實現IUsb接口,這是關鍵點,是調用者實現接口,需求經過事件委託給充電設備自行處理;ui
3.Mobile反射充電設備,經過構造函數注入IUsb;this
代碼清單:spa
1 public interface IUsb { 2 decimal Voltage { get; set; } 3 event System.EventHandler Connecting; 4 }
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="鏈接充電設備" OnClick="btnConnect_Click" /> 19 </div> 20 </form> 21 </body> 22 </html>
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 = "設備無響應"; 22 else { 23 this.Connecting(null, EventArgs.Empty); 24 this.lblVoltage.Text = this.Voltage.ToString(); 25 this.lblMessage.Text = (this.Voltage==0)?"設備無充電功能" 26 : (this.Voltage == Max) ? "瞬間充滿" 27 :"充電中"; 28 } 29 } 30 31 }
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 }
我只是寫個骨架,有興趣的朋友能夠多實現幾個不一樣類型的Usb設備,
而且能夠嘗試擴展Usb接口的功能,好比說爲手機增長拷貝數據的功能,設計
看看鏈接筆記本電腦和充電器的不一樣效果code