I have a TreeView
and I want to enable the context menu when clicking with the right mouse button. It is composed by items from different classes, but they all share the same base class.
So, I was considering to create a FactoryClass
for each different item class that simply returns a custom IContextMenu
interface (that later will be used by some other part of program to actually render the menu).
This is the current workflow I have in mind
- The
TreeView
intercept the right click and request to another class
(let’s call itContextMenuFactory
) to create a Context menu for
that item type ContextMenuFactory
redirect to a specific
factory class associated to the input item type (likeIFooItemContextMenuFactory
)IFooItemContextMenuFactory
class actually create theIContextMenu
instance
What makes difficult this task is the second step.
I don’t know how can I organize my code in order to make it dynamic because the only solution I have in mind it’s just to implement a switch and create the factory class after I have recognized the type.
The ideal way would be to use the container to find the configured implementation, in this way I don’t have to modify every time I create a new item type the switch previously suggested.
5
I would do this:
- For every class that implements
IContextMenu
create a Factory/Creator. For example for a class namedTypeAContextMenu
create aTypeAContextMenuCreator
, forTypeBContextMenu
create aTypeBContextMenuCreator
, etc. Every creator implements the same interface, like sayIContextMenuCreator
, they just have acreate()
method that returns an object of typeIContextMenu
; -
Create a
HashMap
, instantiate all creators and put them in the HashMap with a tag:Map<String,IContextMenuCreator> c = new HashMap<String,IContextMenuCreator>(); creator.put("TYPEA", new TypeAContextMenuCreator()); creator.put("TYPEB", new TypeBContextMenuCreator()); creator.put("TYPEC", new TypeCContextMenuCreator());
-
Then the object you right-click on in the tree view should include the tag of its corresponding
IContextMenuCreator
as a member. -
When you right-click, get the appropriate creator from the
HashMap
. No need for switches. When new types of contextual menus are created you only have to add them in one place.IContextMenu cm = creators.get(tag).create();