Reputation: 15423
I have rows of different types of animals in my Animals table in my database.
I have an IAnimal interface with a Speak method.
I have different animal classes that implement IAnimal interface (Dog, Cat, etc. )
Do you iterate the records check for the type and then instantiate the correct object based on the type and then call their Speak method.
Is that a typical way to use interfaces?
Upvotes: 0
Views: 232
Reputation: 2597
In this instance, the type of relationship you are talking about is a "is a" relationship. A dog is an animal. "Is a" relationships in object oriented design are implemented using a base class, not an Interface.
So you have a base class of Animal. You then have a class of Dog that inherits from Animal.
When you retrieve your data from your database, you would create each animal as it's type, but add to a List of Animal.
Your calling function can then iterate through the List of Animal objects and call Speak without having to know what each object is.
public void MakeAnimalsSpeak()
{
// gets your animals from the database
List<Animal> animals = GetAnimals();
foreach(Animal animal in animals)
{
animal.Speak();
}
}
private List<Animals> GetAnimals()
{
List<Animal> animalsToReturn = new List<Animal>();
// get data from db
// loop through data
// switch on "type" field, create correct object.
// add too List.
return animalsToReturn;
}
Upvotes: 1
Reputation: 13443
If you are trying to represent derived types in a relational database, you have the following options:
It appears that you've selected option 2.
You will typically use the IAnimal interface as a return type of a method or a parameter to another method, rather than instantly calling the speak method right after instantiation.
For example the following code might make sense for interface usage:
public IList<IAnimal> GetAnimals()
{
var animals = new List<IAnimal>();
foreach(var animal in db.Animals)
{
animals.add( // instantiate new animal here)
}
return animals;
}
This would allow a caller to make all the animals speak, regardless of their underlying type. Of course if the interface just has a speak method it probably isn't terribly useful.
Upvotes: 1
Reputation: 56429
No this isn't the typical way, basically you'd have a method that took an instance of the interface, then you could call the Speak
method in there. You don't have to care what concrete type the object you passed in is, the beauty of this is you can add many more types in time and not have to change your implementation.
Something like this:
public void Speak(IAnimal animal)
{
animal.Speak();
}
Upvotes: 2
Reputation: 14521
You don't need to care about the type of your object, if you know it implements IAnimal.
var animal = (IAnimal)animals[i];
animal.Speak();
Check the reference, which includes samples.
Upvotes: 4