Cybercrux

Everything is achievable through technology

interface & abstract class

An interface says to the user that this class will _support these functions_.

For example:

public interface IWorker
{
void DoWork();
}
public class MyInformation : IWorker
{
public void DoWork()
{
//Do your class-specific Work
}
}

var info = new MyInformation();
info.DoWork();

You might ask here – why not just add the method in MyInformation, instead of implementing an interface?

Here’s a situation where it would be useful:

List workers = GetWorkers();
foreach(var worker in workers)
worker.DoWork();

Here we don’t know what kind of objects we’re recieving. All we know is that they will implement any of the methods defined in IWorker. We don’t care how they do it – all we care about is that they support your call.

As for an abstract class:

public abstract class Serializer
{
protected void GetAttributes()
{
//Some default implementation
}
public abstract void SaveObject(String outputPath);
}

We have a serializer class, which has some basic default implementations – but by itself it does nothing. It does not know how to write the output – only how to get the attribute information.

Now you can have a concrete implementation such as :

public class XmlSerializer : Serializer
{
public override void SaveObject(String outputPath)
{
//Do your xml serializing
}
}

Which will serialize it to XML.

Again, you don’t care how they serialize, only that they do it;

List serializers = GetWorkers();
foreach(var serializer in serializers)
serializer.SaveObject(@”C:\out.tmp”);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s