Interfaces
Interfaces provide a way to specify an entire class signature so that other classes can manipulate instances of a class that implements that interface. Got all that? It's actually really simple.Chapter 8, "HttpHandlers and HttpModules," we'll talk about HttpHandlers. An HttpHandler is a class that takes a Web request and does something with it. ASP.NET has a number of handlers. Requests for .aspx pages are handled by the System.Web.UI.PageHandlerFactory class, for example. Every handler implements the IHttpHandler interface so that the framework can manipulate the class and serve pages.The easiest way to explain the interface is to show it to you. Listing 2.15 shows how the .NET Framework defines the IHttpHandler interface.
Listing 2.15. The IHttpHandler interface
C#
VB.NET
public interface IHttpHandler
{
void ProcessRequest(HttpContext context);
bool IsReusable
{
get;
}
}
If you think that the code in Chapter 8), it might look something like Listing 2.16.
Public Interface IHttpHandler
Sub ProcessRequest(context As HttpContext)
ReadOnly Property IsReusable() As Boolean
End Interface
Listing 2.16. An implementation of the IHttpHandler interface
C#
VB.NET
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// do something here
}
public bool IsReusable
{
get { return true; }
}
}
So why might you create an interface? One practical reason would be to define a data access layer for your application. Your interface might have dozens of method signatures that define how to get or save data to a database, while a class that implements the interface does the actual work. You could create several classes that all implement the same interface but interact with different databases (such as SQL Server or Access). If a developer comes along who wants to use yet another database, such as Oracle, she can write her own class that implements your interface and swap out the other class that uses SQL Server. The rest of your application won't break (assuming of course that the implementation is well tested and that the developer knows what she's doing).
Public Class MyHandler
Implements IHttpHandler
Public Sub ProcessRequest(context As HttpContext)
' do something here
End Sub
Public ReadOnly Property IsReusable() As Boolean
Get
Return True
End Get
End Property
End Class