Why use interface ?
The following 2 examples will give bit more insight into use of interfaces. The first example explains how interface can be ploymorphically used. The second one explains how it can be used for multiple-implementation. Both the examples combined also describe a ISP or Interface Segrigation Principle.
Example 1: [Polymorphism] Suppose you have an application that writes data into different devices say HDD, FDD and CDW, in a buffered mode. Any number and any media may be used. It should also be possible plug-in/out any device any time. Each device has its own implementations. How do you ensure that this can be done without knowing the specific implementation of the device?
Solution: Lat them all implement an interface that defines common operations. The application can use the interface to make polymorphic calls.
public interface IMedia
{
void FlushData();
void OpenMedia();
void WriteData(Stream dataStream);
}
public class CDW : IMedia { ... }
public class HDD : IMedia { ... }
public class FDD : IMedia { ... }
public class DataApplication
{
CDW _cdw = new CDW(...);
HDD _hdd = new HDD(...);
FDD _fdd = new FDD(...);
IMedia _mediaDevices[] = new IMedia[] ({_cdw, _hdd, _fdd });
private void SomeDataWriteTask()
{
_cdw.WriteData(someDataStream);
_hdd.WriteData(someDataStream);
_fdd.WriteData(someDataStream);
}
private void Close()
{
foreach(IMedia mediaItem in _mediaDevices)
{
// Ploymorphic call to flush the buffered
// data into correct implementations.
mediaItem.Flush();
}
}
}
Example 2: [Multiple Implementation] Continuing the above example now suppose you have another diagnosis application that needs to check few common performance factors of these devices. The dignostic application need not know the details of these implementations. However the DataApplication (application above) should not have any knowledge of these tasks. How to do this?
Solution: Let each media implement an interface that the diagnostic application can use to operate upon. So the modified design looks like:
public interface IMedia
{
void FlushData();
void OpenMedia();
void WriteData(Stream dataStream);
}
public interface IMediaMonitor
{
long GetSeekSpeed();
long GetSizeInBytes();
void MoveToOffset(long offsetPosition);
}
public class CDW : IMedia, IMediaMonitor { ... }
public class HDD : IMedia, IMediaMonitor { ... }
public class FDD : IMedia, IMediaMonitor { ... }
public class DiagnosisApplication
{
private void DoHealthCheck(IMediaMonitor someMedia)
{
IMediaMonitor mediaDevice = someMedia;
long l1 = mediaDevice.GetSeekSpeed();
long l2 = mediaDevice.GetSizeInBytes();
mediaDevice.MoveToOffset(0);
}
}
Source : from other site..
0 comments :
Post a Comment