Iterator design pattern combination mode (c)

Now that we've looked at page after page can happily set out in the a la carte menu. And now the junior partner wanted to add a dessert of "sub-menu." How to do it? We not only have to support multiple menus, or even support menu menu.

If we can make the dessert menu restaurant menu becomes an element of the set, that the more good. However, according to the current implementation, simply can not do it. What we want is this:

What do we need

Now the real problem we encountered is that our system has reached a level of sophistication, if we do not redesign will not be able to accommodate future increases in demand such as menu or submenu.

So, in our new design, what really needs it?

  • We need some kind of tree structure that can accommodate up menus, sub-menus and menu items
  • We need to be able to walk between the individual to determine for each menu item, and at least the same as it is now easy to use iterators
  • We also need more flexibility to be able to walk between the menu items. For example, you may only need to traverse the dessert menu, or you can traverse the entire restaurant menu (including dessert menu included).

Defined combined mode

Yes, we want to introduce another model to solve this problem. We did not give up iterator - it's still part of our solution - however, issue management menu has reached a new dimension iterator can not be solved. So, we will be a few steps back, use a combination of modes to achieve.

Combined mode : allows you to combine objects into tree structures to represent "whole / part" hierarchy. Combination allows customers in a consistent way to deal with individual objects and their combinations.

Let us take for example the menu thinking it all: this model can create a tree structure, with nested menus and menu items in the same group structure. By menus and items placed in the same structure, we have created a "whole / part" hierarchy of menus and menu items that is composed of the object tree. But it can be considered as a whole, like a big rich menu.

Once you have a wealth of large eggs, we can use this model to "unified treatment of individual objects and combinations of objects." what does this mean? It means that if we have a menu tree structure, sub-menus and submenus possibly with a menu item, then any menu is a kind of a "combination."

因为它既可以包含其他菜单,也可以包含菜单项。个别对象只是菜单项--并未持有其他对象。就像你将看到,使用一个遵照组合模式的设计,让我们能够写出简单的代码,就能够对整个菜单结构应用相同的操作。

结合图来描述如下:

组合模式的类图如下:

了解完组合模式的种种,在下次的推文中,我们将用于实际操作。我们利用组合模式设计菜单,并且使用菜单,以此来巩固加深。敬请期待吧。

爱生活,爱学习,爱感悟,爱挨踢

Guess you like

Origin www.cnblogs.com/dimple91/p/11068379.html