Say you have a number of similar objects (e.g. instances of the class Person). Each of these instances can belong to a number of Groups, also represented by a class. To stick with the examples of people, one person could be a member of the group Employees and SoccerTeam and Family or something.
How would one model this scenario in object oriented design, so that when you remove a person from a group, that change is also being reflected in the persons' list of groups.
My approach would be something like this:
import sets
class Person(object):
def __init__(self, name):
self.name = name
self.groups = sets.Set()
def register(self, group):
self.groups.add(group)
def unregister(self, group):
self.groups.remove(group)
def getGroups(self):
return self.groups
class Group(object):
def __init__(self, name):
self.name = name
self.members = sets.Set()
def add(self, person):
self.members.add(person)
person.register(self)
def remove(self, person):
self.members.remove(person)
person.unregister(self)
def getMembers(self):
return self.members
peter = Person("Peter")
family = Group("PetersFamily")
family.add(peter)
# peter is now member of PetersFamily
family.remove(peter)
# peter has been removed from PetersFamily
My gut feeling says this isn't very nice, as calling Person.register
from outside a Group instance would break things. What is the right and elegant way to do this?
register()
andunregister()
acceseable only fromGroup
class? For example, in Java you could place both classes in the same package and use package visibility for the methodsregister()
andunregister()
. – Leonid Semyonov 4 hours ago