Structural Design Patterns: Composite Pattern
48 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the primary role of the Composite class in the context of the Composite Design Pattern?

  • It manages the lifecycle of individual component instances.
  • It defines a common interface for leaves and composites.
  • It stores and defines behavior for components having children. (correct)
  • It solely focuses on manipulating files without child components.
  • What type of files can the Directory class contain?

  • Just directory types.
  • Only image and video files.
  • Any type of files, including other directories. (correct)
  • Only text files.
  • What is the purpose of the Component class in the design pattern described?

  • To define the interface for objects with dynamic responsibilities. (correct)
  • To provide a base for concrete decorators.
  • To implement the concrete operations of the class.
  • To hold the state of the decorators.
  • What type of relationship exists between the Decorator and the ConcreteComponent?

    <p>HAS-A relationship.</p> Signup and view all the answers

    Which method is responsible for adding files to the Directory class?

    <p>addFile()</p> Signup and view all the answers

    What issue arises from overusing inheritance in the beverage class design?

    <p>It may lead to a class explosion.</p> Signup and view all the answers

    What does the getSize() method in the Directory class compute?

    <p>Total size of all child files and directories.</p> Signup and view all the answers

    In the provided implementation, what type does the TextFile class return in its getType() method?

    <p>txt</p> Signup and view all the answers

    How do ConcreteDecorators enhance the behavior of the component?

    <p>By adding new methods before or after existing methods.</p> Signup and view all the answers

    What method do all subclasses of Beverage override?

    <p>cost()</p> Signup and view all the answers

    In the context of the Composite Design Pattern, what does the term 'leaf' refer to?

    <p>A component that cannot have children.</p> Signup and view all the answers

    Which of the following condiments is NOT listed in the coffee shop example?

    <p>Vanilla syrup</p> Signup and view all the answers

    What is the purpose of the File interface in this design pattern implementation?

    <p>To define methods that both composite and leaf classes must implement.</p> Signup and view all the answers

    How is the size calculated for the Directory object containing child files?

    <p>It aggregates the sizes from each child file.</p> Signup and view all the answers

    In the approach to avoid class explosion, which variable type is added to the Beverage class?

    <p>boolean</p> Signup and view all the answers

    Why is the cost() method not declared as abstract in the modified Beverage class design?

    <p>To enable dynamic addition of condiments during runtime.</p> Signup and view all the answers

    What is the primary purpose of the Composite design pattern?

    <p>To compose objects into tree structures and treat them uniformly</p> Signup and view all the answers

    Which of the following is NOT a characteristic of the Composite pattern?

    <p>Relies on linear rather than hierarchical structures</p> Signup and view all the answers

    In the context of the Composite pattern, what is a Leaf object?

    <p>A single object that does not have children</p> Signup and view all the answers

    What role does the Composite object play in the Composite pattern?

    <p>It manages child elements and defines operations for them</p> Signup and view all the answers

    Which of the following scenarios is most appropriate for applying the Composite pattern?

    <p>When a part-whole relationship exists in a hierarchical structure</p> Signup and view all the answers

    How are Leaf and Composite objects related in the Composite pattern?

    <p>Both are defined as the same data type through inheritance or interface</p> Signup and view all the answers

    When implementing a Composite design pattern, what is a key step to ensure uniform treatment of components?

    <p>Utilize the same interface or extend from a base class for both types</p> Signup and view all the answers

    Which of the following best illustrates the concept of the Composite pattern in real life?

    <p>A hierarchy of employees in a company viewable as a directory</p> Signup and view all the answers

    What does the cost method in the abstract class Beverage signify?

    <p>It allows concrete components to define their own costs.</p> Signup and view all the answers

    What is the role of the Decorator pattern in the context of beverage selection?

    <p>To dynamically extend functionality without subclassing.</p> Signup and view all the answers

    Which class serves as the base class for both concrete components and decorators?

    <p>Component</p> Signup and view all the answers

    In the given example, which of the following can be considered a concrete component?

    <p>DarkRoast</p> Signup and view all the answers

    What is the typical function of the abstract class CondimentDecorator?

    <p>To define a common interface for condiment-related decorators.</p> Signup and view all the answers

    How do Concrete Decorators differ from Concrete Components?

    <p>They contain instances of components to add behavior.</p> Signup and view all the answers

    What can be inferred about the description variable in the Beverage class?

    <p>It serves as a default descriptor until overridden.</p> Signup and view all the answers

    What would be the immediate consequence of not overriding the cost method in a concrete component?

    <p>The component will always return a default cost of 0.</p> Signup and view all the answers

    What is the primary purpose of the getDescription method in the Beverage class?

    <p>To provide a base description for all beverages</p> Signup and view all the answers

    Which statement accurately describes the relationship between DarkRoast and Beverage?

    <p>DarkRoast is a concrete class that extends Beverage</p> Signup and view all the answers

    What does the Mocha class do when it is constructed with a Beverage?

    <p>It sets the instance variable for decoration purposes</p> Signup and view all the answers

    How does the cost for a beverage decorated with Mocha calculate its total cost?

    <p>It sums the cost of the base beverage with the Mocha cost</p> Signup and view all the answers

    What would b2 = new Mocha(b2) imply in terms of object-oriented principles?

    <p>A beverage is being decorated with additional functionality</p> Signup and view all the answers

    Which class explicitly requires that the methods getDescription and cost be overridden?

    <p>CondimentDecorator</p> Signup and view all the answers

    What is the output of the following code snippet: Beverage b2 = new DarkRoast(); b2 = new Mocha(b2);?

    <p>Dark roast, Mocha Rs.70</p> Signup and view all the answers

    Why must the cost method be overridden in the concrete classes of decorators?

    <p>To enable calculation of total cost including both beverage and condiment</p> Signup and view all the answers

    What is the final cost of a beverage that is made up of DarkRoast, Mocha, and Whip?

    <p>Rs 130</p> Signup and view all the answers

    Why can the Mocha class not be instantiated directly without a beverage?

    <p>Mocha requires a constructor argument that is a Beverage.</p> Signup and view all the answers

    What does the decorator pattern allow you to do with an object's behavior?

    <p>You can add or remove responsibilities from an object at runtime.</p> Signup and view all the answers

    What is a disadvantage of using the decorator pattern?

    <p>It can complicate code maintainability due to numerous similar decorators.</p> Signup and view all the answers

    When the cost method is called on the beverage that is a combination of DarkRoast and Mocha, what cost is initially returned from DarkRoast?

    <p>Rs 20</p> Signup and view all the answers

    In the example given, what is the role of the Whip class in relation to the other beverages?

    <p>It enhances the beverage created by wrapping the existing one.</p> Signup and view all the answers

    How would the classes DarkRoast, Mocha, and Whip relate to each other in terms of class hierarchies?

    <p>DarkRoast is the superclass, while Mocha and Whip are decorators.</p> Signup and view all the answers

    What is necessary before you can instantiate the Mocha class?

    <p>A concrete Beverage must be passed in its constructor.</p> Signup and view all the answers

    Study Notes

    STRUCTURAL DESIGN PATTERNS

    • Structural design patterns compose classes or objects into larger structures, and then define ways to use these structures

    COMPOSITE PATTERN

    • Also known as: Object Tree
    • Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects
    • From the name, "Composite" means the combination or made from different parts
    • This pattern provides a solution to operate on groups of objects and single objects in a similar way
    • Real-life examples include file-directory structures, where a node can be a directory or a file
      • Even though directories and files are different types of objects, they can be treated similarly (e.g., checking the size of a directory, which is the sum of sizes of all files within that directory)
    • Another real-life example is employee hierarchy structure (CEO, managers, employees)
      • All employees, managers and the CEO are instances of a person
    •  Structure of the composite pattern:
        1. Composite Object: An object that contains other objects. This can be a directory (file folder)
        1. Leaf Object: A single object that does not have children (e.g., a file).

    WHERE CAN WE USE COMPOSITE PATTERN?

    • When you want to represent a part-whole relationship in a tree structure (Objects can be represented in a tree structure hierarchy)
    • Composite and individual objects are treated uniformly
    • Need to define parent-child relationships

    STEPS TO IMPLEMENT COMPOSITE DESIGN PATTERN

    • Define leaf and composite objects as the same data type
    • Implement an interface or extend a class
    • Write common methods for all leaf and composite objects
    • Leaf node performs its own desired behavior
    • Composite object writes a customized function or each child of this node can call this function

    STRUCTURE & PARTICIPANTS

    • Component: Declares an interface for objects in the composition, and implements default behaviors common to all.
    • Leaf: Represents leaf objects in the composition; doesn't have children; defines behavior for primitive objects.
    • Composite: Defines behaviors for components having children; stores child components; implements child-related operations in the component interface
    • Client: Manipulates objects in the composition through the component interface.

    UML DIAGRAM FOR COMPOSITE DESIGN PATTERN IMPLEMENTATION

    • Shown in the image will create an interface for " File ".
    • Will have two different classes one for directory type and second for classes other than directory (.txt, .doc, etc).

    IMPLEMENTING COMPOSITE DESIGN PATTERN IN JAVA

    • Example for file directory structure
    • Create child file and root directories.
    • Get size of files and directories

    COMPOSITE DESIGN PATTERN CLASS IMPLEMENTATION(JAVA)

    • Classes for file and directory types (e.g., TextFile, Directory)
    • Directory implements File and stores a list of File objects
    • TextFile implements File and has size

    APPLICATION CLASS (JAVA)

    • Implements main method for testing the code
    • Create TextFile objects child1 and child2
    • Create Directory object root
    • Add child1 and child2 to root
    • Print sizes of child1 and root.

    PROS AND CONS OF COMPOSITE PATTERN

    • Pros:
      • Data represented as a tree structure
      • Same operations on different object types
      • Reduces overhead for handling different types of objects
      • Open/Closed Principle: introducing new elements without breaking existing code
    • Cons:
      • Objects must be compatible
      • Complexity can increase

    DECORATOR PATTERN

    • Decorator is a structural design pattern that lets you attach new behaviors to objects by placing them inside special wrapper objects that contain the behaviors
    • Uses composition instead of inheritance to extend an object's functionality at runtime.
    • Also known as Wrapper
    • Wrap a component with any number of decorators (e.g., wrapping a gift, putting it in a box, wrapping the box).
    • Change component behavior by adding new functionality before and/or after method calls to the component
    • Provides an alternative to subclassing for expanding behavior

    WHERE CAN DECORATOR PATTERN BE USED?

    • Attach additional responsibilities to objects at runtime without altering code using these objects
    • Use when it's hard to extend object behavior with inheritance
    • Programming languages with the final keyword used to prevent further extension of a class

    UML CLASS DIAGRAM & PARTICIPANTS

    • Component: Defines an interface for objects that can have responsibilities added dynamically
    • Decorator: Decorators implement the same interface as the component; have a relationship with the object they extend (a has-a relationship).
    • ConcreteComponent: Object to be enhanced dynamically. Inherits from Component.
    • ConcreteDecorator: Decorators that enhance the state of the component, can add new methods, adding new behavior before or after existing methods.

    COFFEE SHOP EXAMPLE

    • Introduces a coffee shop, serving four beverage types (house blend, dark roast, decaf, espresso).
    • Starts by using inheritance but quickly realizes this leads to many classes for various combinations of beverages and condiments.
    • Example of "class explosion" caused by overuse of inheritance.
    • Suggests alternative approach to handle condiments.

    APPROACH 1

    • Add boolean variables in Beverage class to represent condiments (milk, soy, mocha, whip)
    • Override the cost method in specific concrete Beverage classes

    APPROACH 2

    • Use Decorator pattern to dynamically add condiments
    • Components are Beverage classes (DarkRoast, etc.)
    • Decorators are classes that add behavior to the Beverage object (e.g., Whip, Mocha)

    UML DIAGRAM OF DECORATOR PATTERN (EXAMPLE: MOCA AND WHIP DECORATIONS)

    • Graphic shows a DarkRoast class.
    • Shows how Mocha and Whip components add new behaviors, building up functionality

    DECORATOR PATTERN CLASS DEFINITION (EXAMPLE: MOCA CLASS)

    • Implments Beverage class
    • Has a beverage that it wraps

    IMPORTANT NOTE ON DECORATOR PATTERN

    • Decorator is a subclass of the Component class
    • You cannot create a ConcreteDecorator without a ConcreteComponent

    PROS AND CONS OF DECORATOR PATTERN

    • Pros:
      • Easily extend objects' behavior without creating subclasses.
      • Add and remove behaviors at runtime
      • Combine multiple behaviors using decorators.
    • Cons:
      • Hard to remove a specific decorator from the stack.
      • Code maintainability can be challenging as decorators can get numerous and similar; difficult to maintain and distinguish

    QUESTIONS

    • Composite: Composing Objects into Tree Structures
    • Decorator: Adding Behaviors to Objects by Placing them Inside Wrappers

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Structural Design Patterns PDF

    Description

    Explore the Composite pattern, a key structural design pattern that allows the composition of objects into tree structures. This quiz will cover its principles, real-life applications like file systems and employee hierarchies, and how it enables uniform treatment of individual and composite objects.

    More Like This

    Composite Design Pattern
    12 questions

    Composite Design Pattern

    SelfSufficientRadon avatar
    SelfSufficientRadon
    Composite Design Pattern
    6 questions

    Composite Design Pattern

    SelfSufficientRadon avatar
    SelfSufficientRadon
    Use Quizgecko on...
    Browser
    Browser