Structural Design Patterns: Composite Pattern

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

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. (B)</p> Signup and view all the answers

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

<p>addFile() (A)</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. (D)</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. (C)</p> Signup and view all the answers

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

<p>txt (A)</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. (B)</p> Signup and view all the answers

What method do all subclasses of Beverage override?

<p>cost() (D)</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. (B)</p> Signup and view all the answers

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

<p>Vanilla syrup (D)</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. (C)</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. (B)</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 (C)</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. (D)</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 (D)</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 (A)</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 (B)</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 (B)</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 (A)</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 (A)</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 (B)</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 (D)</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. (B)</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. (B)</p> Signup and view all the answers

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

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

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

<p>DarkRoast (C)</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. (D)</p> Signup and view all the answers

How do Concrete Decorators differ from Concrete Components?

<p>They contain instances of components to add behavior. (B)</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. (C)</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. (D)</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 (D)</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 (C)</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 (C)</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 (C)</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 (B)</p> Signup and view all the answers

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

<p>CondimentDecorator (D)</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 (C)</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 (A)</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 (B)</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. (A)</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. (D)</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. (B)</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 (B)</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. (A)</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. (A)</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. (C)</p> Signup and view all the answers

Flashcards

Composite Pattern

A design pattern that lets you compose objects into tree structures and treat them as individual objects.

Composite Object

An object in a composite pattern that can contain other objects (children).

Leaf Object

A single object in a composite pattern that does not contain any other objects (no children).

Part-Whole Relationship

A hierarchical relationship where a whole is composed of parts, and parts can be composed of further parts.

Signup and view all the flashcards

Uniform Treatment

The ability to treat both composite and leaf objects in a similar way, e.g., calculating sizes.

Signup and view all the flashcards

Component Interface

The interface that declares a common set of methods for both composite and leaf objects.

Signup and view all the flashcards

Employee Hierarchy

An example of a composite structure where managers (composite) contain employees (leafs).

Signup and view all the flashcards

File-Directory Structure

A typical example of using the composite pattern where files and folders compose the tree.

Signup and view all the flashcards

Composite Class

A class that can contain other objects (children) in a hierarchical structure

Signup and view all the flashcards

Leaf Class

A class that cannot contain other objects (no children)

Signup and view all the flashcards

Component Interface (File)

An interface that defines common methods for both composite and leaf objects

Signup and view all the flashcards

File Object

Represents a file (either a leaf or a composite)

Signup and view all the flashcards

Directory Object

A composite class that holds other files or directories as children.

Signup and view all the flashcards

Calculating Size

The ability to calculate the total size of composite objects by aggregating the sizes of their children.

Signup and view all the flashcards

Uniform Treatment

The ability to treat both composite and leaf objects in a similar way through the interface (like getting size).

Signup and view all the flashcards

Decorator Pattern

Extends an object's functionality dynamically, offering a flexible alternative to inheritance.

Signup and view all the flashcards

Component

Abstract class defining a common interface for both concrete components and decorators.

Signup and view all the flashcards

Concrete Component

An object that can have additional behaviors added to it. It can stand alone, or be decorated.

Signup and view all the flashcards

Decorator

Abstract class for adding responsibilities to a component.

Signup and view all the flashcards

Concrete Decorator

Specific decorator that holds a component and adds responsibilities.

Signup and view all the flashcards

Beverage

Example class of a concrete component for cost calculation.

Signup and view all the flashcards

cost() method

Abstract method in Beverage that must be overridden for calculating the cost of an item

Signup and view all the flashcards

CondimentDecorator

Abstract class for decorators that add condiments, extending a beverage.

Signup and view all the flashcards

Decorator Pattern

A design pattern that adds new functionalities to existing objects dynamically without modifying their structure.

Signup and view all the flashcards

Component Interface

A common interface that both the base object and decorators follow in the decorator pattern.

Signup and view all the flashcards

Decorator

A class that adds responsibilities to the component object without changing its structure.

Signup and view all the flashcards

ConcreteComponent

The class that defines the core functionality of the object you want to enhance.

Signup and view all the flashcards

ConcreteDecorator

A class that adds specific decorator behaviors to the component object.

Signup and view all the flashcards

Class Explosion

Creating too many classes due to excessive inheritance; hard to maintain.

Signup and view all the flashcards

Decorator Composition(Approach 1)

Adds state variables to a component to control optional functionalities (e.g., condiments).

Signup and view all the flashcards

Beverage (Abstract)

An abstract class defining a beverage (coffee) and its cost calculation.

Signup and view all the flashcards

HouseBlend, DarkRoast, Decaf, Espresso

Concrete types of beverages (coffee).

Signup and view all the flashcards

Cost Method

A method in the beverage class to calculate the cost.

Signup and view all the flashcards

Decorator Pattern

An object-oriented design pattern that dynamically adds or modifies the behavior of an existing object by wrapping it with additional functionality

Signup and view all the flashcards

Component

Interface for objects being decorated. Defines the basic operations for the objects.

Signup and view all the flashcards

Decorator

Wraps the Component, adding additional responsibilities. Extends the base functionality without changing the core.

Signup and view all the flashcards

Beverage

Base class for drinks in the example

Signup and view all the flashcards

getDescription()

Method in the Beverage class returning a String description of the drink.

Signup and view all the flashcards

cost()

Method in the Beverage class returning an integer representing the cost

Signup and view all the flashcards

CondimentDecorator

Base class for decorators that add extra items to beverages, like Mocha or Whip

Signup and view all the flashcards

DarkRoast

A specific type of coffee drink in decorator pattern example code

Signup and view all the flashcards

Mocha

Example of a condiment in beverage shop, a specific topping/extra for a drink

Signup and view all the flashcards

Espresso

Base Beverage type in the example. Another example of component class

Signup and view all the flashcards

Decaf

An extra possible type of Beverage

Signup and view all the flashcards

Decorator Pattern

Adds responsibilities to an object dynamically without altering its structure. Uses composition rather than inheritance.

Signup and view all the flashcards

Decorator

An object that enhances the functionality of another object (the component) by wrapping it.

Signup and view all the flashcards

Component

The object that receives the decorator's added functionality; the core object.

Signup and view all the flashcards

Concrete Decorator

A specific implementation of a decorator, providing a particular enhancement.

Signup and view all the flashcards

Concrete Component

A specific class of the component.

Signup and view all the flashcards

Constructor in Decorator

Decorator class' constructor takes a Component object as an argument to wrap it. Essential for the pattern to work.

Signup and view all the flashcards

Decorator Cost Calculation

The cost of a decorated object is calculated sequentially, adding the costs of each decorator to the component's cost.

Signup and view all the flashcards

Decorator Usage (Order)

Decorators are applied sequentially to a component. The order of decoration affects the final result (cost).

Signup and view all the flashcards

Decorator Pros

Extensibility, flexibility, and combining behaviors at runtime without extending classes.

Signup and view all the flashcards

Decorator Cons

Complexity in maintaining the decorators, difficulty in removing specific wrappers.

Signup and view all the flashcards

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

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
Composite Risk Management Quiz
26 questions

Composite Risk Management Quiz

IllustriousHoneysuckle avatar
IllustriousHoneysuckle
Use Quizgecko on...
Browser
Browser