SlideShare a Scribd company logo
Composite Pattern
(A Structural Pattern)
Composite
Intent
 Compose objects into tree structures to
  represent part-whole hierarchies. Composite
  lets clients treat individual objects and
  compositions of objects uniformly.
Motivation
 Graphics applications like drawing editors and schematic capture systems let users build complex diagrams out of
    simple components.

 The user can group components to form larger components, which in turn can be grouped to form still larger
    components.

 A simple implementation could define classes for graphical primitives such as Text and Lines plus other classes that
    act as containers for these primitives.

 But there's a problem with this approach: Code that uses these classes must treat primitive and container objects
    differently, even if most of the time the user treats them identically. Having to distinguish these objects makes the
    application more complex.

 The Composite pattern describes how to use recursive composition so that clients don't have to make this distinction.

 The key to the Composite pattern is an abstract class that represents both primitives and their containers.

 For the graphics system, this class is Graphic. Graphic declares operations like Draw that are specific to graphical
    objects. It also declares operations that all composite objects share, such as operations for accessing and managing its
    children.

 The subclasses Line, Rectangle, and Text (see preceding class diagram) define primitive graphical objects. These
    classes implement Draw to draw lines, rectangles, and text, respectively. Since primitive graphics have no child
    graphics, none of these subclasses implements child-related operations.

 The Picture class defines an aggregate of Graphic objects. Picture implements Draw to call Draw on its children, and
    it implements child-related operations accordingly. Because the Picture interface conforms to the Graphic interface,
    Picture objects can compose other Pictures recursively.
Motivation
Applicability
Applicability
  Use the Composite pattern when you want to represent
   part-whole hierarchies of objects.

  you want clients to be able to ignore the difference
   between compositions of objects and individual objects.
   Clients will treat all objects in the composite structure
   uniformly.
Structure
Structure
Participants
 Component (Graphic)
    declares the interface for objects in the composition.
    implements default behavior for the interface common to all classes, as
     appropriate.
    declares an interface for accessing and managing its child components.
    (optional) defines an interface for accessing a component's parent in the
     recursive structure, and implements it if that's appropriate.

 Leaf (Rectangle, Line, Text, etc.)
    represents leaf objects in the composition. A leaf has no children.
    defines behavior for primitive objects in the composition.

 Composite (Picture)
    defines behavior 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.
Collaborations
Clients use the Component class interface to interact
 with objects in the composite structure.

If the recipient is a Leaf, then the request is handled
 directly.

If the recipient is a Composite, then it usually
 forwards requests to its child components, possibly
 performing additional operations before and/or after
 forwarding.
Consequences
 The Composite pattern
    defines class hierarchies consisting of primitive objects and composite objects.
     Primitive objects can be composed into more complex objects, which in turn
     can be composed, and so on recursively. Wherever client code expects a
     primitive object, it can also take a composite object.

     makes the client simple. Clients can treat composite structures and individual
      objects uniformly. Clients normally don't know (and shouldn't care) whether
      they're dealing with a leaf or a composite component. This simplifies client
      code, because it avoids having to write tag-and-case-statement-style functions
      over the classes that define the composition.

     makes it easier to add new kinds of components. Newly defined Composite or
      Leaf subclasses work automatically with existing structures and client code.
      Clients don't have to be changed for new Component classes.

     can make your design overly general. The disadvantage of making it easy to
      add new components is that it makes it harder to restrict the components of a
      composite. Sometimes you want a composite to have only certain components.
      With Composite, you can't rely on the type system to enforce those constraints
      for you. You'll have to use run-time checks instead.
Implementation
 Explicit parent references. Maintaining references from child components to
  their parent can simplify the traversal and management of a composite
  structure. The parent reference simplifies moving up the structure and
  deleting a component. The usual place to define the parent reference is in the
  Component class. Leaf and Composite classes can inherit the reference and
  the operations that manage it.

 Sharing components. It's often useful to share components, for example, to
  reduce storage requirements. But when a component can have no more than
  one parent, sharing components becomes difficult. A possible solution is for
  children to store multiple parents. But that can lead to ambiguities as a
  request propagates up the structure.

 Maximizing the Component interface. One of the goals of the Composite
  pattern is to make clients unaware of the specific Leaf or Composite classes
  they're using. To attain this goal, the Component class should define as many
  common operations for Composite and Leaf classes as possible. The
  Component class usually provides default implementations for these
  operations, and Leaf and Composite subclasses will override them.
Implementation
 Declaring the child management operations. Although the Composite
  class implements the Add and Remove operations for managing
  children, an important issue in the Composite pattern is which classes
  declare these operations in the Composite class hierarchy. Should we
  declare these operations in the Component and make them
  meaningful for Leaf classes, or should we declare and define them
  only in Composite and its subclasses?


    Defining the child management interface at the root of the class
     hierarchy gives you transparency, because you can treat all
     components uniformly. It costs you safety, however, because clients
     may try to do meaningless things like add and remove objects from
     leaves.

    Defining child management in the Composite class gives you safety,
     because any attempt to add or remove objects from leaves will be
     caught at compile-time in a statically typed language like C++. But you
     lose transparency, because leaves and composites have different
Implementation
 If you opt for safety, then at times you may lose type information and have to convert a component into a composite.
 How can you do this without resorting to a type-unsafe cast?

 One approach is to declare an operation Composite* GetComposite() in the Component class. Component provides a
 default operation that returns a null pointer. The Composite class redefines this operation to return itself through the
 this pointer:
Implementation
GetComposite lets you query a component to see if
 it's a composite. You can perform Add and Remove
 safely on the composite it returns.
Implementation
Of course, the problem here is that we don't treat all
  components uniformly.

The only way to provide transparency is to define default
  Add and Remove operations in Component.

That creates a new problem: There's no way to implement
  Component::Add without introducing the possibility of it
  failing. You could make it do nothing, but that ignores an
  important consideration; that is, an attempt to add
  something to a leaf probably indicates a bug.

In that case, the Add operation produces garbage. You
  could make it delete its argument, but that might not be
  what clients expect.
Implementation
 Should Component implement a list of Components? You might be tempted to define the set of
   children as an instance variable in the Component class where the child access and management
   operations are declared. But putting the child pointer in the base class incurs a space penalty for
   every leaf, even though a leaf never has children. This is worthwhile only if there are relatively few
   children in the structure.

 Child ordering. Many designs specify an ordering on the children of Composite. In the earlier
   Graphics example, ordering may reflect front-to-back ordering. If Composites represent parse trees,
   then compound statements can be instances of a Composite whose children must be ordered to
   reflect the program.

 Caching to improve performance. If you need to traverse or search compositions frequently, the
   Composite class can cache traversal or search information about its children. The Composite can
   cache actual results or just information that lets it short-circuit the traversal or search. Changes to a
   component will require invalidating the caches of its parents. Bounding box example.

 Who should delete components? In languages without garbage collection, it's usually best to make a
   Composite responsible for deleting its children when it's destroyed. An exception to this rule is when
   Leaf objects are immutable and thus can be shared.

 What's the best data structure for storing components? Composites may use a variety of data
   structures to store their children, including linked lists, trees, arrays, and hash tables. The choice of
   data structure depends (as always) on efficiency. In fact, it isn't even necessary to use a general-
   purpose data structure at all. Sometimes composites have a variable for each child, although this
   requires each subclass of Composite to implement its own management interface.
Sample Code
Sample Code
Sample Code
Sample Code
Assignment
 Create an application that


 1) parses an HTML document or an HTML string.
 2) creates an HTML DOM internally for managing objects.
 3) is able to handle both container tags such as DIV, LI, etc and leaf
  tags such as IMG, BR, HR, etc.
 4) has all standard DOM manipulation functions such Add Node,
  Remove Node, etc.
 5) Every node has some standard behaviour such as GetHTML(),
  GetInnerHTML(), Render(), etc.

 For parsing use .NET’s XML API.
 For rest, implement from scratch.

More Related Content

What's hot

Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Anuja Arosha
 
Design patterns
Design patternsDesign patterns
Design patterns
Luis Goldster
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
Livares Technologies Pvt Ltd
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
Sanae BEKKAR
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
Jyaasa Technologies
 
Facade pattern
Facade patternFacade pattern
Facade pattern
JAINIK PATEL
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
Anjan Kumar Bollam
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
Shakil Ahmed
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Creational pattern
Creational patternCreational pattern
Creational pattern
Himanshu
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
Jonathan Simon
 
Solid principles
Solid principlesSolid principles
Solid principles
Monica Rodrigues
 
Design pattern - Facade Pattern
Design pattern - Facade PatternDesign pattern - Facade Pattern
Design pattern - Facade Pattern
Mudasir Qazi
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 

What's hot (20)

Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Design pattern - Facade Pattern
Design pattern - Facade PatternDesign pattern - Facade Pattern
Design pattern - Facade Pattern
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 

Viewers also liked

The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
Akshat Vig
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Pattern
eprafulla
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
Somenath Mukhopadhyay
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - AdapterManoj Kumar
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
guy_davis
 

Viewers also liked (6)

The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 

Similar to Composite pattern

Sda 9
Sda   9Sda   9
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
Sangharsh agarwal
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design PatternsDang Tuan
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Luis Valencia
 
Composite pattern.pptx
Composite pattern.pptxComposite pattern.pptx
Composite pattern.pptx
SeetharamNageshAppe1
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
bonej010
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
LK394
 
Hello Android
Hello AndroidHello Android
Hello Android
Trong Dinh
 
2 class use case
2 class use case2 class use case
2 class use case
Minal Maniar
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
AnmolPandita7
 
React patterns
React patternsReact patterns
React patterns
Naimish Verma
 
Uml - An Overview
Uml - An OverviewUml - An Overview
Uml - An Overview
Raj Thilak S
 
Mapping objects to_relational_databases
Mapping objects to_relational_databasesMapping objects to_relational_databases
Mapping objects to_relational_databasesIvan Paredes
 
Bad Smells in Code
Bad Smells in CodeBad Smells in Code
Bad Smells in Code
Özge Nur KOÇ
 
Design patterns
Design patternsDesign patterns
Design patterns
Vignesh Nethaji
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsJason Townsend, MBA
 
Design pattern (week 2)
Design pattern (week 2)Design pattern (week 2)
Design pattern (week 2)stanbridge
 

Similar to Composite pattern (20)

Sda 9
Sda   9Sda   9
Sda 9
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
Composite pattern.pptx
Composite pattern.pptxComposite pattern.pptx
Composite pattern.pptx
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
 
Hello Android
Hello AndroidHello Android
Hello Android
 
2 class use case
2 class use case2 class use case
2 class use case
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
React patterns
React patternsReact patterns
React patterns
 
Uml - An Overview
Uml - An OverviewUml - An Overview
Uml - An Overview
 
Mapping objects to_relational_databases
Mapping objects to_relational_databasesMapping objects to_relational_databases
Mapping objects to_relational_databases
 
Bad Smells in Code
Bad Smells in CodeBad Smells in Code
Bad Smells in Code
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
 
Design pattern (week 2)
Design pattern (week 2)Design pattern (week 2)
Design pattern (week 2)
 

More from Shakil Ahmed

Algorithm
AlgorithmAlgorithm
Algorithm
Shakil Ahmed
 
B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-tree
Shakil Ahmed
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
Observer pattern
Observer patternObserver pattern
Observer pattern
Shakil Ahmed
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
Shakil Ahmed
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
Shakil Ahmed
 
Facade pattern
Facade patternFacade pattern
Facade pattern
Shakil Ahmed
 
Command pattern
Command patternCommand pattern
Command pattern
Shakil Ahmed
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
Shakil Ahmed
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
Shakil Ahmed
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
Shakil Ahmed
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
Shakil Ahmed
 
iOS 5
iOS 5iOS 5
Ios development
Ios developmentIos development
Ios development
Shakil Ahmed
 
Graph
GraphGraph
Lowest common ancestor
Lowest common ancestorLowest common ancestor
Lowest common ancestor
Shakil Ahmed
 
Segment tree
Segment treeSegment tree
Segment tree
Shakil Ahmed
 
Tree & bst
Tree & bstTree & bst
Tree & bst
Shakil Ahmed
 
Trie tree
Trie treeTrie tree
Trie tree
Shakil Ahmed
 

More from Shakil Ahmed (20)

Algorithm
AlgorithmAlgorithm
Algorithm
 
B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-tree
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Command pattern
Command patternCommand pattern
Command pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
iOS 5
iOS 5iOS 5
iOS 5
 
Ios development
Ios developmentIos development
Ios development
 
Graph
GraphGraph
Graph
 
Lowest common ancestor
Lowest common ancestorLowest common ancestor
Lowest common ancestor
 
Segment tree
Segment treeSegment tree
Segment tree
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Trie tree
Trie treeTrie tree
Trie tree
 

Recently uploaded

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 

Recently uploaded (20)

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 

Composite pattern

  • 2. Composite Intent Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • 3. Motivation  Graphics applications like drawing editors and schematic capture systems let users build complex diagrams out of simple components.  The user can group components to form larger components, which in turn can be grouped to form still larger components.  A simple implementation could define classes for graphical primitives such as Text and Lines plus other classes that act as containers for these primitives.  But there's a problem with this approach: Code that uses these classes must treat primitive and container objects differently, even if most of the time the user treats them identically. Having to distinguish these objects makes the application more complex.  The Composite pattern describes how to use recursive composition so that clients don't have to make this distinction.  The key to the Composite pattern is an abstract class that represents both primitives and their containers.  For the graphics system, this class is Graphic. Graphic declares operations like Draw that are specific to graphical objects. It also declares operations that all composite objects share, such as operations for accessing and managing its children.  The subclasses Line, Rectangle, and Text (see preceding class diagram) define primitive graphical objects. These classes implement Draw to draw lines, rectangles, and text, respectively. Since primitive graphics have no child graphics, none of these subclasses implements child-related operations.  The Picture class defines an aggregate of Graphic objects. Picture implements Draw to call Draw on its children, and it implements child-related operations accordingly. Because the Picture interface conforms to the Graphic interface, Picture objects can compose other Pictures recursively.
  • 5. Applicability Applicability Use the Composite pattern when you want to represent part-whole hierarchies of objects. you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.
  • 8. Participants  Component (Graphic)  declares the interface for objects in the composition.  implements default behavior for the interface common to all classes, as appropriate.  declares an interface for accessing and managing its child components.  (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.  Leaf (Rectangle, Line, Text, etc.)  represents leaf objects in the composition. A leaf has no children.  defines behavior for primitive objects in the composition.  Composite (Picture)  defines behavior 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.
  • 9. Collaborations Clients use the Component class interface to interact with objects in the composite structure. If the recipient is a Leaf, then the request is handled directly. If the recipient is a Composite, then it usually forwards requests to its child components, possibly performing additional operations before and/or after forwarding.
  • 10. Consequences  The Composite pattern  defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed, and so on recursively. Wherever client code expects a primitive object, it can also take a composite object.  makes the client simple. Clients can treat composite structures and individual objects uniformly. Clients normally don't know (and shouldn't care) whether they're dealing with a leaf or a composite component. This simplifies client code, because it avoids having to write tag-and-case-statement-style functions over the classes that define the composition.  makes it easier to add new kinds of components. Newly defined Composite or Leaf subclasses work automatically with existing structures and client code. Clients don't have to be changed for new Component classes.  can make your design overly general. The disadvantage of making it easy to add new components is that it makes it harder to restrict the components of a composite. Sometimes you want a composite to have only certain components. With Composite, you can't rely on the type system to enforce those constraints for you. You'll have to use run-time checks instead.
  • 11. Implementation  Explicit parent references. Maintaining references from child components to their parent can simplify the traversal and management of a composite structure. The parent reference simplifies moving up the structure and deleting a component. The usual place to define the parent reference is in the Component class. Leaf and Composite classes can inherit the reference and the operations that manage it.  Sharing components. It's often useful to share components, for example, to reduce storage requirements. But when a component can have no more than one parent, sharing components becomes difficult. A possible solution is for children to store multiple parents. But that can lead to ambiguities as a request propagates up the structure.  Maximizing the Component interface. One of the goals of the Composite pattern is to make clients unaware of the specific Leaf or Composite classes they're using. To attain this goal, the Component class should define as many common operations for Composite and Leaf classes as possible. The Component class usually provides default implementations for these operations, and Leaf and Composite subclasses will override them.
  • 12. Implementation  Declaring the child management operations. Although the Composite class implements the Add and Remove operations for managing children, an important issue in the Composite pattern is which classes declare these operations in the Composite class hierarchy. Should we declare these operations in the Component and make them meaningful for Leaf classes, or should we declare and define them only in Composite and its subclasses?  Defining the child management interface at the root of the class hierarchy gives you transparency, because you can treat all components uniformly. It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves.  Defining child management in the Composite class gives you safety, because any attempt to add or remove objects from leaves will be caught at compile-time in a statically typed language like C++. But you lose transparency, because leaves and composites have different
  • 13. Implementation If you opt for safety, then at times you may lose type information and have to convert a component into a composite. How can you do this without resorting to a type-unsafe cast? One approach is to declare an operation Composite* GetComposite() in the Component class. Component provides a default operation that returns a null pointer. The Composite class redefines this operation to return itself through the this pointer:
  • 14. Implementation GetComposite lets you query a component to see if it's a composite. You can perform Add and Remove safely on the composite it returns.
  • 15. Implementation Of course, the problem here is that we don't treat all components uniformly. The only way to provide transparency is to define default Add and Remove operations in Component. That creates a new problem: There's no way to implement Component::Add without introducing the possibility of it failing. You could make it do nothing, but that ignores an important consideration; that is, an attempt to add something to a leaf probably indicates a bug. In that case, the Add operation produces garbage. You could make it delete its argument, but that might not be what clients expect.
  • 16. Implementation  Should Component implement a list of Components? You might be tempted to define the set of children as an instance variable in the Component class where the child access and management operations are declared. But putting the child pointer in the base class incurs a space penalty for every leaf, even though a leaf never has children. This is worthwhile only if there are relatively few children in the structure.  Child ordering. Many designs specify an ordering on the children of Composite. In the earlier Graphics example, ordering may reflect front-to-back ordering. If Composites represent parse trees, then compound statements can be instances of a Composite whose children must be ordered to reflect the program.  Caching to improve performance. If you need to traverse or search compositions frequently, the Composite class can cache traversal or search information about its children. The Composite can cache actual results or just information that lets it short-circuit the traversal or search. Changes to a component will require invalidating the caches of its parents. Bounding box example.  Who should delete components? In languages without garbage collection, it's usually best to make a Composite responsible for deleting its children when it's destroyed. An exception to this rule is when Leaf objects are immutable and thus can be shared.  What's the best data structure for storing components? Composites may use a variety of data structures to store their children, including linked lists, trees, arrays, and hash tables. The choice of data structure depends (as always) on efficiency. In fact, it isn't even necessary to use a general- purpose data structure at all. Sometimes composites have a variable for each child, although this requires each subclass of Composite to implement its own management interface.
  • 21. Assignment  Create an application that  1) parses an HTML document or an HTML string.  2) creates an HTML DOM internally for managing objects.  3) is able to handle both container tags such as DIV, LI, etc and leaf tags such as IMG, BR, HR, etc.  4) has all standard DOM manipulation functions such Add Node, Remove Node, etc.  5) Every node has some standard behaviour such as GetHTML(), GetInnerHTML(), Render(), etc.  For parsing use .NET’s XML API.  For rest, implement from scratch.