Registering/deregistering object with list

B

Bryan

A Person can belong to one group.
I want to be able to set the group using these two methods:

PersonA.Group = GroupA

or

GroupA.Add(PersonA)

In the Set method of Person.Group, the Person adds itself to the
Groups list:
Set
_Group.Remove(Me) ' Remove self from previous group
value.Add(Me) ' Add self to new group
_Group = value ' Set field
End Set

So when using PersonA.Group = GroupA, PersonA has knowledge of what
group it belongs to, and it also registers with GroupA.
So immediately after doing:
PersonA.Group = GroupA,
....the following is true:
GroupA.Contains(PersonA) = True.

Coming the other direction, when saying: GroupA.Add(PersonA), I have
in a OnListChanged sub of the Group class:
(pseudo code)
Sub ListChanged(e)
if e.ChangeType = Add Then
e.Person.Group= Me
ElseIf e.ChangeType = Delete
e.Person.Group= Nothing
End If
End Sub

So after doing:
GroupA.Add(Person)
....the following is true:
PersonA.Group = GroupA.

The problem is that this creates an infinite loop. When Something is
added/removed to Group, the Person.Group setter is called. And when
the Person.Group setter is called, it triggers the Group ListChanged
event.

I am working on a messy solution with shared variables that allow the
ListChanged subs let the Person.Group setter know that it is being set
by the ListChanged event, and vice versa so they don't call each
other.
I am looking for a clean pattern. How would you solve this problem?
 
B

Bill McCarthy

Hi Bryan,

try changing the set to:

Set
If value Is _Group Then return
If _Group IsNot Nothing Then _Group.Remove(Me)
value.Add(Me) ' Add self to new group
_Group = value ' Set field
End Set
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top