Data relationship problem
i have a problem in my class-design.
Ich have 2 classes:
public class A {
public B[] _bs;
public string _name;
}
public class B {
public string getAName() {
// The problem
}
}
In words: I have two classes A and B. The class A has many B's and a B has only one A!
Thats easy. But now i need a attribute from A through a method of B.
Sure I can create something like
public class B {
public A _parent;
public string getAName() {
return _parent._name;
开发者_JAVA百科 }
}
But this, i think, is no good design...
My programming language is C# but this is a general problem..
What other possibilities can I use?
Your solution is the normal way to do it. I can't even think of another possible way to do it without doing something ridiculous like decompiling the dll. Possibly keeping a list of A's and having the B find which A it's in, but still very wrong.
Is there any reason you don't want to expose the entire A
for your B
?
public class B
{
public A A {get;set;}
}
So instead of:
var aName = b.getAName();
... you'd say:
var aName = b.A.Name;
(In my world, you made a public Name
property and made the _name
field private.)
But speaking generally, it sounds like your concern is with having A
point to B
and B
point to A
at the same time. This is standard practice when representing bi-directional relationships like the one you're talking about. There's nothing wrong with it.
Have the method belong to A, and have A invoke a method of B (possibly passing A's information to B as a parameter). You're correct in thinking it's a questionable design decision to have B responsible for distributing/processing A's information.
Two suggestions:
- If the property is fixed, it can be parameter to B constructor so B still doesnt know about A
- A implement an interface and the interface expose specific property(ies) only and B have reference to that. You can simply pass that it, set it or get fancy and use dependency injection
public class A
{
public List<B> _listOfB;
public string Name { get; set; }
public List<B> ListOfB
{
get { return _listOfB; }
}
public A()
{
ListOfB = new List<B>();
}
public void AddB(B b)
{
B.InstanceOfA = this;
ListOfB.Add(b);
}
}
public class B
{
public A InstanceOfA { get; set; }
}
Add a B's to A:
A a = new A();
a.Name = "AAAA";
A.AddB(new B());
A.AddB(new B());
A.AddB(new B());
The this:
foreach(B b in A.ListOfB)
{
Console.WriteLine(b.InstanceOfA.Name);
}
Would result in:
AAAA
AAAA
AAAA
But as always there is ofcourse there is more than one "good" solution :) (for instance you could add a constructor to B where you pass a reference to A)
(Take care that you use AddB() and not ListOfB.Add(), otherwise InstanceOfA is not set (and ofcourse you can set it yourself and add it to ListOfB anyway)
Hope this helps.
精彩评论