WebForm版demo,模拟手机Usb接口充电

材料清单:Mobile(手机),MiniCharger(迷你充电器),IUsb(USB接口),

设计思路:

1.声明IUsb约定对象之间的交互方式,其中包含一个事件;

2.Mobile实现IUsb接口,这是关键点,是调用者实现接口,需求通过事件委托给充电设备自行处理;

3.Mobile反射充电设备,通过构造函数注入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="连接充电设备" 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 = "设备无响应";

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     }
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

我只是写个骨架,有兴趣的朋友可以多实现几个不同类型的Usb设备,
并且可以尝试扩展Usb接口的功能,比如说为手机增加拷贝数据的功能,

看看连接笔记本电脑和充电器的不同效果

 

你可能感兴趣的:(webform)