Monday, 1 December 2014

Interface

-:Interface :-



An interface looks like a class, but has no implementation.

-The only thing it contains are declarations of events, indexers, methods and/or properties.
-The reason interfaces only provide declarations is because they are inherited by classes and structs, which must provide an implementation for each interface member declared.

Interfaces in C# are provided as a replacement of multiple inheritance.
-Because C# does not support multiple inheritance, it was necessary to incorporate some other method so that the class can inherit the behavior of more than one class, avoiding the problem of name ambiguity that is found in C++.
-With name ambiguity, the object of a class does not know which method to call if the two base classes of that class object contain the same named method.

Purposes of Interfaces
-create loosely coupled software
-support design by contract (an implementor must provide the entire interface)
-allow for pluggable software
-allow different objects to interact easily
-hide implementation details of classes from each other
-facilitate reuse of software

EXAMPLE:-


public class FileLog : ILog
{
    public void Log(string text)
    {
        // write text to a file
    }
}

public class DatabaseLog : ILog
{
    public void Log(string text)
    {
        // write text to the database
    }
}

public interface ILog
{
    void Log(string text);
}

public class SomeOtherClass
{
    private ILog _logger;

    public SomeOtherClass(ILog logger)
    {
        // I don't know if logger is the FileLog or DatabaseLog
        // but I don't need to know either as long as its implementing ILog
        this._logger = logger;
        logger.Log("Hello World!");
    }    
}

No comments:

Post a Comment