SlideShare ist ein Scribd-Unternehmen logo
1 von 21
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.

Weitere ähnliche Inhalte

Was ist angesagt?

Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibilityShakil Ahmed
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patternsAmit Kabra
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 

Was ist angesagt? (20)

Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
State
StateState
State
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Design pattern
Design patternDesign pattern
Design pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Proxy Pattern
Proxy PatternProxy Pattern
Proxy Pattern
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 

Andere mochten auch

The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator PatternAkshat 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 Patterneprafulla
 
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 Patternguy_davis
 

Andere mochten auch (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
 

Ähnlich wie Composite pattern

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
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternsbonej010
 
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 1LK394
 
Mapping objects to_relational_databases
Mapping objects to_relational_databasesMapping objects to_relational_databases
Mapping objects to_relational_databasesIvan Paredes
 
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
 

Ähnlich wie 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 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)
 
Css uml
Css umlCss uml
Css uml
 

Mehr von Shakil Ahmed

Mehr von Shakil Ahmed (15)

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
 
Command pattern
Command patternCommand pattern
Command 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
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search Techniques
 

Kürzlich hochgeladen

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Kürzlich hochgeladen (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

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.