Reputation: 939
My group and I are making a program, where we have a tree structure. In this tree structure we have made it such that a category can contain it self. The program is based on your expenses, so an example could be:
You have bought 4 milk. The 4 items of milk are placed in the category "Milk". Each entry of milk has the price (along with other individual information) in another class which category aggregates.
The trick is that we want the category class to be able to contain it self, so:
The category "milk" is part of the category "Dairy Products", which in terms are part of the category "Groceries".
The reason we want it to be like that, is so we can move batches of products at the time. So if you want to move Milk to a category called "Morning Stuff" you wouldn't have to move every single one, but instead just the entire category.
The picture is how our current category class is modelled, but we were told we couldn't do it without much further explanation. Does UML allow this? If not, how can we model it with UML?
Upvotes: 4
Views: 14310
Reputation: 5585
Yes it is allowed, but in most cases it is better to aggregate an abstraction (abstract class or interface) in order to preserve Polymorphism rather than the item its self; see the Composite Pattern for an example.
This is known as the Interface Segregation Principle and is one of the five SOLID principles
Upvotes: 3
Reputation: 14101
Yes, UML allows associations from a class to itself. Likewise aggregations and even compositions are allowed this way.
The image you posted shows an aggregation while from your description I would have chosen a composition (filled diamond): a category has one or no parent; a category is somewhat defined by its children; if a category gets deleted all children are deleted as well.
A longer comparison between aggregation and composition can be found here.
Upvotes: 6