开发者

Any real example of using interface related to multiple inheritance

I m trying to understand Interfaces so that I can implement them in my programs but I m not able to imagine how should i use them. Also give me some eg of using them with multip开发者_StackOverflow中文版le inheritance in C#


A good example for an interface is a repository pattern. Your interface will define methods like Get, GetAll, Update, Delete, etc. No implementation, just function signatures.

Then, you can write a 'concrete' implementation of that class to work with, say, MySQL. Your UI should only refer to the interface, though.

Later, if you decide to change to Microsoft SQL, you write another concrete implementation, but your UI code doesn't have to change (much).

Multiple inheritance doesn't exist in C#, in the sense that you can only inherit from one 'concrete' class; though you can inherit (or 'implement') as many interfaces as you want.


I am writing a video game. In this video game I apply different forces to objects in the game. Thrust forces, impact forces, gravitational forces. While they are calculated differently, they all have the same basic elements. I need to call an update function that will evaluate the force and add the force to the object it's attached to.

So, what I've done is create an IForce interface that has an update function for its signature. All of my forces implement this interface:

public interface IForce
{
    void Update(Particle particle, GameTime gameTime);
}

Here is a sample implementation.

public class Spring : IForce
{
    private Particle ThisParticle;
    private Particle ThatParticle;

    private float K;

    public Spring(Particle thisParticle, Particle thatParticle, float k)
    {
        ThisParticle = thisParticle;
        ThatParticle = thatParticle;
    }

    public void Update(Particle particle, GameTime gameTime)
    {            
        float X = Vector3.Length(ThisParticle - ThatParticle);

        ThisParticle.Forces.Add(K * X);
    }
}

The update function has a simplified spring force update to make it easier to understand.

This helps in a few ways.

I can completely change the way a force is calculated without effecting other parts of my code. I do this all the time. Along the same lines, it is rediculously easy for me to add new forces. As long as it implements the IForce interface I know it will mesh well with my existing code.

Another way it helps is with handling a large number of forces. I have a force registry that has a List of IForce. Since all forces implement that interface and have an Update function it's very easy to update all the forces in my game. When I create the force I add it to the list. Then, I loop through the list and call each elements update function without worrying about what type of force it is and all my forces update.

I use interfaces every day in a lot of different situations. They are fantastic!


Note :Interface is used to restrict and access the methods or events etc from differents classes at any cost, It means we can defined many more methods inside any class but when we are calling methods through Interface means we want only other than restricted methods. In the program below User1 can use Read & Write both but User2 can Write and Execute. See this Program below.........

namespace ExplConsole
{
    class Program 
    {
        static void Main ()
        {
            System.Console.WriteLine("Permission for User1");
            User1 usr1 = new Test(); // Create instance.
            usr1.Read(); // Call method on interface.
            usr1.Write();
            System.Console.WriteLine("Permission for User2");
            User2 usr2 = new Test();
            usr2.Write();
            usr2.Execute();
            System.Console.ReadKey();
        }
    }
    interface User1
    {
        void Read();
        void Write();
    }
    interface User2
    {
        void Write();
        void Execute();
    }
    class Test : NewTest,User1, User2 
    {
        public void Read()
        {
            Console.WriteLine("Read");
        }
        public void Write()
        {
            Console.WriteLine("Write");
        }
    }
    class NewTest 
    {
        public void Execute()
        {
            Console.WriteLine("Execute");
        }
    }
}

Output:

    Permission for User1
    Read
    Write
    Permission for User2
    Write
    Execute


Interfaces simply define a contract of the public elements (e.g. properties, methods, events) for your object, not behavior.

interface IDog
{
    void WagTail();    //notice no implementation
    ISound Speak();    //notice no implementation
}

class Spaniel : IDog
{
    public void WagTail()
    {
        Console.WriteLine("Shook my long, hairy tail");
    }

    public ISound Speak()
    {
        return new BarkSound("yip");
    }

}

class Terrier : IDog
{
    public void WagTail()
    {
        Console.WriteLine("Shook my short tail");
    }

    public ISound Speak()
    {
        return new BarkSound("woof");
    }
}

UPDATE

In "real examples" I use interfaces with: - Unit Testing - GENERICS (e.g. Repository, Gateway, Settings)

interface Repository<T>{
    T Find(Predicate<T>);
    List<T> ListAll();
}

interface Gateway<T>{
    T GetFrom(IQuery query);
    void AddToDatabase(IEntity entityItem);
}

interface Settings<T>{
    string Name { get; set; }
    T Value { get; set; }
    T Default { get; }
}


Here is one (in Java, but this is not important since they're similiar): In my project I've created simple interface:

public interface Identifiable<T> {
    public T getId();
}

Which is simple replacement to some sorts of annotations. The next step: I've made all entity classes implement this interface.

The third step is to write some syntax-sugar-like methods:

public <T> List<T> ids(List<? extends Identifiable<T> entities) { ... }

This was just an example.

The more complex example is something like validation rules: you have some validation engine (probably written by you) and a simple interface for rule:

public interface ValidationRule {
    public boolean isValid(...);
}

So, this engine requires the rules to be implemented by you. And of course there will be multiple inheritance since you'll certainly wish more then a single rule.


Multiple inheritance is about having a class be usable in multiple situations: [pseudo code]

interface Shape {
    // shape methods like draw, move, getboundingrect, whatever.
}

interface Serializable {
    // methods like read and write
}

class Circle : public Shape, public Serializable {
    // TODO: implement Shape methods
    // TODO: implement Serializable methods
}

// somewhere later
{
    Circle circle;
    // ...
    deserializer.deserialize(circle);
    // ...
    graphicsurface.draw(circle);
    // ...
    serializer.serialize(circle);
}

The idea is that your Circle class implements two different interfaces that are used in very different situations.


Sometimes being too abstract just gets in the way and referring to implementation details actually clarifies things. Therefore, I'll provide the close to the metal explanation of interfaces that made me finally grok them.

An interface is just a way of declaring that a class implements some virtual functions and how these virtual functions should be laid out in the class's vtable. When you declare an interface, you're essentially giving a high-level description of a virtual function table to the compiler. When you implement an interface, you're telling the compiler that you want to include the vtable referred to by that interface in your class.

The purpose of interfaces is that you can implicitly cast a class that implements interface I to an instance of interface I:

interface I {
    void doStuff();
}

class Foo : I {
    void doStuff() {}

    void useAnI(I i) {}
}

var foo = new Foo();
I i = foo;  // i is now a reference to the vtable pointer for I in foo.
foo.useAnI(i);  // Works.  You've passed useAnI a Foo, which can be used as an I.


The simple answer, in my opinion, and being somewhat new to interfaces myself is that implementing an interface in a class essentially means: "This class MUST define the functions (and parameters) in the interface".

From that, follows that whenever a certain class implements the interface, you can be sure you are able to call those functions.

If multiple classes which are otherwise different implement the same interface, you can 'cast' them all to the interface and call all the interface functions on them, which might have different effects, since each class could have a different implementation of the functions.

For example, I've been creating a program which allows a user to generate 4 different kinds of maps. For that, I've created 4 different kind of generator classes. They all implement the 'IGenerator' interface though:

public interface IGenerator {
    public void generateNow(int period);
}

Which tells them to define at least a "public generateNow(int period)" function.

Whatever generator I originally had, after I cast it to a "IGenerator" I can call "generateNow(4)" on it. I won't have to be sure what type of generator I returned, which essentially means, no more "variable instanceof Class1", "variable instanceof Class2" etc. in a gigantic if statement anymore.


Take a look at something you are familiar with - ie a List collection in C#. Lists define the IList interface, and generic lists define the IList interface. IList exposes functions such as Add, Remove, and the List implements these functions. There are also BindingLists which implement IList in a slightly different way.

I would also recommend Head First Design Patterns. The code examples are in Java but are easily translated into C#, plus they will introduce you to the real power of interfaces and design patterns.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜