Thinking questions

We don't just have to support multiple menus , We also support the menu in the menu . How do you deal with this new design requirement ? P355

  • 【 Tips 】 In our new design , The following three points are really needed : P354

    • We need some kind of attribute structure , You can hold a menu 、 Submenus and menu items
    • We need to be sure to be able to swim between items in each menu , And at least as easy as using an iterator now
    • We also need to be able to move more flexibly between menu items . For example , Maybe you just need to go through the dessert menu , Or you can go through the restaurant's entire menu ( Including dessert menu )
  • Provide an interface , Unify the superclass of menu and menu item
    • Interface contains common methods for menus and menu items , The execution method in the menu is to execute the same method in each subitem in turn
    • Interface contains menu specific methods of adding, deleting, modifying and checking subitems , The method of adding, deleting and checking subitems in menu items is to throw out directly UnsupportedOperationException
    • Can pass instanceof Determine whether the current item is a menu or a menu item

Portfolio model

Allows you to combine objects into a tree structure to represent ” whole / part “ hierarchy . Composition allows customers to handle individual objects and composition of objects in a consistent way .

characteristic

  • Apply the same operations to composite and individual objects , That is, you can ignore the differences between object combinations and individual objects P357
  • In exchange for transparency by violating the principle of Single Responsibility Design , It's not just about managing hierarchies , It also includes the operation of managing composition and leaf nodes , To treat composition and leaf nodes alike P367

Empty the iterator : An empty object ( The command mode mentioned ) An example of . Empty the iterator , hasNext() Never return false , next() Never return null ( I think it can be thrown out NoSuchElementException), remove() Always throw out UnsupportedOperationException . P372

Thinking questions

public class Waitress {
MenuComponent allMenus; public Waitress(MenuComponent allMenus) {
this.allMenus = allMenus;
} public void printMenu() {
allMenus.print();
} public void printVegetarianMenu() {
Iterator iterator = allMenus.createIterator();
System.out.println("\nVEGETARIAN MENU\n----");
while (iterator.hasNext()) {
MenuComponent menuComponent = (MenuComponent)iterator.next();
try {
if (menuComponent.isVegetarian()) {
menuComponent.print();
}
} catch (UnsupportedOperationException e) {}
}
}
}

printVegetarianMenu() Method has only menu items print() Methods can be called , Never call the menu ( Combine ) Of print() Method . Can you tell me why ? P373

  • When using iterator traversal, all nodes will be traversed ( Including composite nodes and leaf nodes ), And the composite node will print all the sub node information , If you call the print() , Some leaf nodes will be printed repeatedly .

Thinking questions

Match the following patterns and descriptions : P379

The strategy pattern : Encapsulating interchangeable behavior , And use delegation to decide which one to use

Adapter pattern : Change the interface of one or more classes

Iterator pattern : Provides a way to traverse the collection , Without exposing the implementation of the collection

Appearance mode : Simplify the interface of a group of classes

Portfolio model : Customers can treat a collection of objects as well as individual objects equally

Observer mode : When a state changes , Allow a group of objects to be informed of

Thinking and thinking

  • This idea has been used in many places before , Binary tree 、trie Tree structure and line tree structure allow nodes to form a tree structure to represent ” whole / part “ Hierarchical structure , And provide a consistent way to deal with non leaf nodes and leaf nodes ( Inside the method of a non leaf node, it processes and calls the same method of a child node according to specific logic )

This article was first published on the official account : Man Fu Zhu Ji ( Click to view the original ) Open source in GitHub :reading-notes/head-first-design-patterns

Head First Design patterns —— 11. Combine (Composite) More articles on patterns

  1. Design patterns C++ describe ----11. Combine (Composite) Pattern

    One . give an example This example is from the book , Suppose there is a company whose structure is as follows : Its structure is very much like a tree , The human resources department and the finance department have no sub nodes , Only a specific company has its children . And what matters most is , Each layer of it has a very similar structure . The code implementation is as follows : / ...

  2. C++ Design pattern implementation -- Combine (Composite) Pattern

    One . give an example This example is from the book , If there is a company's organization structure, such as the following : Its structure is very much like a tree , The human resources department and the finance department have no sub nodes , Only detailed companies have child nodes . And what matters most is , The structure of each layer is very similar . Code implementation example ...

  3. Java Realize the combination (Composite) Pattern

    Class diagram /** * Trees The overall * * @author stone * */ public class Tree { private TreeNode root; // The root node public Tree(St ...

  4. Combine (composite) Pattern

    Definition Combine objects into a tree structure to represent “ part - whole ” Hierarchical structure , Make the use of single object and composite object consistent Portfolio model (Composite) Combine small objects into a tree structure , Enables users to manipulate composite objects as if they were manipulating a single object . Group ...

  5. 8、 ... and 、 A combination of structural patterns (Composite) Pattern

    A composite pattern belongs to the structural pattern of an object , Sometimes called part - The whole model , The composite pattern organizes objects into a tree structure , It can be used to describe the connection between the whole and the part . It enables the client to treat simple elements as well as composite elements . When the hierarchy of parts and the whole is reflected in the demand , With ...

  6. Design patterns -11 The flyweight pattern (Flyweight Pattern)

    1. Pattern motivation In the process of object-oriented programming , Sometimes there is the problem of creating a large number of instances of the same or similar objects . Creating so many objects will consume a lot of system resources , It's a bottleneck in system performance . The Heyuan pattern is to extract the common parts of the same or similar objects ...

  7. java Design patterns -----11、 The proxy pattern

    Proxy Patterns are also called proxy patterns , Is one of the design patterns of stereotypes , It can provide a proxy for other objects (Proxy) To control access to this object . The so-called agent , It refers to having and acting element ( The proxied object ) Classes with the same interface , The client must pass the proxy ...

  8. Java Design pattern — Combine (Composite)

    Reprint please indicate the source :http://blog.csdn.net/guolin_blog/article/details/9153753 I heard that your company recently launched a new e-book reading application , The market reaction was very good , There are also ...

  9. Java Design patterns 11: Appearance mode

    Appearance mode Appearance mode is the structural mode of an object , External communication with a subsystem must be through a unified appearance object . Appearance patterns are a high-level interface , Makes the subsystem easier to use . Examples of hospitals Modern software systems are more complex . If we compare a hospital to a hospital ...

  10. JS Common design patterns (11)—— Intermediary model

    The mediator object allows objects to refer to each other without being shown , So that the coupling is loose , And they can change their interaction independently . For example , For the sake of safety , Find a trusted intermediary to trade . buyers A Give the money to the agency B, And then from it ...

Random recommendation

  1. Use NDK c++ Build a Android application

    Use NDK c++ Build a Android application One . Tools ADT( Integrated eclipse,cdt,ndk plug-in) NDK ( Use it to compile c/c++ Program ) JDK (Java Development kit ) ANT(ecl ...

  2. Many are the same jar The order of reference when it exists

    cause : Today one aar The package works well in the test environment , Use soapui The test returns normally , Running in the local environment will always report abnormal database connection , After inspection , It's because of the lack of ojdbc dependent jar The bag caused . A new one aar package ...

  3. thorough Callable And Runnable Two interfaces Get thread return result

    Today, we came across a business scenario where we need to get the result returned by the thread , So I learned Callable Interface . Let's take a look at the following example : public class ThreadTest { public static void mai ...

  4. python Reptile scrapy install +pymongo Installation

    my :python2.7 edition     32 position Be careful scrapy Only support 2.7 And above . 1. install python 2. install pip install pip I won't go into that , A lot of online teaching pip Pay attention to update during installation , If pip edition ...

  5. Back end solution WeChat H5 payment Format error of merchant parameter Method

    The problem is shown in the figure : Back end solutions :  Back in mweb_url Don't visit this link directly after , Use... On the current page js window.location.href = mweb_url That's all you need to do

  6. python Use in queue Realize the Joseph Ring ( Joseph's question ) solve

    Joseph's question : It's an application of mathematics : It is known that n personal ( To number 1,2,3...n respectively ) Sit around a round table . From the number k People began to count , Count to m The man of : His next man from 1 Start counting , Count to m And the man of : In accordance with the ...

  7. 05-02 Java One dimensional array 、 Memory allocation 、 Array operation

    Definition of array dynamic initialization /* Array : A container for storing multiple elements of the same data type . Define format : A: data type [] Array name ; B: data type Array name []; give an example : A:int[] a; Define a int An array of types a change ...

  8. linux Get help documentation

    stay linux I don't know how to use it , It can be used man or info Check it out. . man -f And whatis The orders are the same . man -k And apropos The orders are the same . And these two commands are very similar , It's all about searching , find ...

  9. Grand Theft in the city season 5 / The complete Leverage Thunder download

    Season five Leverage Season 5 (2012) Watch it :TNT The TV network has been cut down < Urban bandit >(Leverage), It's been on air to the end of 5 The season's modern Robin Hood Series ends this year , Such a decision is right for &l ...

  10. In the code parameters payload What does that mean? ???

    In the code parameters payload What does that mean? ???