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?

Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)Jubayer Al Mahmud
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patternsAmit Kabra
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 

Was ist angesagt? (20)

Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Design pattern
Design patternDesign pattern
Design pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Visitor pattern
Visitor patternVisitor pattern
Visitor pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 

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 (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
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight 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
 
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
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
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
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 

Kürzlich hochgeladen (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
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
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

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.