How deep do you take the Has-a when it comes to Object Oriented Design?
If I say a car has a certain number of tires, a tire size, a tire brand, then I am guessing I could make a class like this:
public class Car
{
public int TireCount {get;set;}
public float TireSize {get;set;}
public string TireBrand {get;set;}
}
On the other hand, I could make Tire a class and then make that a property of the cl开发者_开发百科ass Car like so:
public class Tire
{
public int Count {get;set;}
public float Size {get;set;}
public string Brand {get;set;}
}
public class Car
{
public Tire tire {get;set;}
}
What is the better way? How deep do I take the relationship? Is it possible to over Object if that there is such as saying?
As deep as it makes sense to go for your application.
In your example, your Car
class would have multiple properties related to tires...so a Tire
class (or collection of Tire
s) makes sense. Probably something like:
public class Tire
{
public float Size {get; set;}
public string Brand {get; set;}
}
public class Car
{
public List<Tire> Tires {get; private set;}
}
Then you could do:
Car myCar = new Car();
// Some initialization here
int tireCount = myCar.Tires.Count();
To get the count of tires.
Personally, I would have "Size" and "Brand" be members of Tire, since they're specific to a specific type of Tire.
Car, on the other hand, should probably have a collection of Tires, since you could (theoretically) have multiple tires, of differing types.
I would do it more like:
public class Tire
{
public float Size {get;set;}
public string Brand {get;set;}
}
public class Car
{
public IList<Tire> Tires {get; private set;}
}
I would go until I'm sure I wont have to duplicate the information
in that case I might need an instance of the tire only
精彩评论