patterncsharpModerate
Cats and Dogs at the Petshop
Viewed 0 times
thedogspetshopandcats
Problem
I had a test before and had to do this task:
Create classes:
The class
We may add new pet to container using method
Which hierarchy of classes is the best solution of this problem?
Write short code to demonstrate your solution. Your code should include class (interface) aggregation, inheritance, should use .NET BCL collections or generics, and should implement exception handling.
My answer:
```
class Dog : IPet
{
public string Name;
public string Breed;
public Dog()
{
Name = "";
Breed = "";
}
public string MyName
{
get
{
return Name;
}
set
Create classes:
Cat, Dog and Petshop. Types Cat and Dog have fields Name and Breed and method Introduce() which prints text "I'm (Name) of (Breed). I'm a cat (or dog)".The class
Petshop collects different pets in its container.We may add new pet to container using method
AddPet(), and we may display information about all pets by calling method IntroduceAll().Which hierarchy of classes is the best solution of this problem?
Write short code to demonstrate your solution. Your code should include class (interface) aggregation, inheritance, should use .NET BCL collections or generics, and should implement exception handling.
My answer:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
interface IPet
{
string MyName { get; set; }
string MyBreed { get; set; }
void Introduce();
}Catclass Cat : IPet
{
string Name;
string Breed;
public Cat()
{
Name = "";
Breed = "";
}
public string MyName
{
get
{
return Name;
}
set
{
Name = value;
}
}
public string MyBreed
{
get
{
return Breed;
}
set
{
Breed = value;
}
}
public void Introduce()
{
Console.WriteLine("I'm " + Name + " of " + Breed + " I'm a cat");
}
}Dog```
class Dog : IPet
{
public string Name;
public string Breed;
public Dog()
{
Name = "";
Breed = "";
}
public string MyName
{
get
{
return Name;
}
set
Solution
One mistake could be using
instead you could have a
instead of comparing types and then calling
Other thing could be having a parameterized constructor, since you are instantiating the objects for
List in your class PetShop List objList = new List();instead you could have a
List and then your method AddPet should expect a parameter of type IPet , add Cat and Dog objects to that list. Later in your method IntroduceAll you could have done:public void IntroduceAll()
{
foreach (IPet element in objList)
{
element.Introduce();
}
}instead of comparing types and then calling
Introduce method, this would show the polymorphic behaviour. Other thing could be having a parameterized constructor, since you are instantiating the objects for
Cat and Dog and then setting properties.Code Snippets
List<Object> objList = new List<object>();public void IntroduceAll()
{
foreach (IPet element in objList)
{
element.Introduce();
}
}Context
StackExchange Code Review Q#96944, answer score: 14
Revisions (0)
No revisions yet.