SlideShare a Scribd company logo
1 of 20
Download to read offline
Composite Pattern



            by

Somenath Mukhopadhyay
   som@som-itsolutions.com

    Structural pattern

 Compose objects into a tree structure to
represent part-whole relationship

 An abstract class represents both primitives and
containers

 The client handles both the primitives and their
containers in the same fashion
Tree structure of the Composite Pattern
Applicability




    To represent part-whole hierarchy

 To make the client ignorant about whether it is
interacting with an individual object or a composite
object
Class Diagram
Example – base class Shape
class Shape
{
public:
              Shape(){}
              virtual void Add(unsigned int id)
              {
                            throw LeafClassTypeException();
              };
              virtual void Remove(unsigned int id){};

              //leaf classes will not override it..however, it will be overridden by the composite class.
              virtual Shape* GetChild(unsigned int id)
              {
                            throw LeafClassTypeException();
              };

              //Using this reference the "Chain of Responsibility" can be implemented
              virtual Shape* GetParentOfComponent()
              {
                            return ParentOfComponent;
              };

              virtual void SetParentOfComponent(Shape* s)
              {
                            ParentOfComponent = s;
              }

              virtual void Display(){};


              virtual Shape* FindItem(unsigned int id); //implementation afterwards

              virtual ~Shape(){};

protected:
              Shape* ParentOfComponent;
              unsigned int resource_id;
};
Iterator and the FindItem function
typedef map <unsigned int, Shape*, less<unsigned int> > theMap;

theMap Resource_Map;
theMap::iterator theIterator;

Shape* Shape::FindItem(unsigned int id)
{
     theIterator = Resource_Map.begin();
            while (theIterator != Resource_Map.end())
            {
            theIterator = Resource_Map.find(id);
            Shape* s = (*theIterator).second;
            theIterator++;
            return s;
            }

             return NULL;
}
A leaf class - Point
class Point : public Shape
{
public:
              Point():x_Coord(0),y_Coord(0){}
              Point(int x, int y):x_Coord(x), y_Coord(y){}
              Point(const Point& p)
              {
                             x_Coord = p.x_Coord;
                             y_Coord = p.y_Coord;
              }
              Point& operator = (const Point& p)
              {
                             x_Coord = p.x_Coord;
                             y_Coord = p.y_Coord;

                            return *this;
             }

             virtual void Display()
             {
                           cout<<"X Coordinate is:"<<x_Coord<<endl;
                           cout<<"Y Coordinate is:"<<y_Coord<<endl;
             }

             int X_COORD()
             {
                       return x_Coord;
             }

             int Y_COORD()
             {
                       return y_Coord;
             }

             virtual ~Point(){}
private:
             int x_Coord;
             int y_Coord;
};
A leaf class – line – a final class as well
//class Line is working as a leaf class.. Lets implement it as a final class
class Line : public Shape
{
private:
             //private constructor
             Line(unsigned int id):begin(0,0),end(0,0)
             {
                          resource_id = id;
                          Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this));
             }
             //private constructor
             Line(unsigned int id, Point a, Point b):begin(a),end(b)
             {
                          resource_id = id;
                          Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this));
             }
             //private copy constructor
             Line(const Line& in){ }
             //private assignment operator
             Line& operator=(const Line& in){ }
public:
             virtual void Display()
             {
                          cout<<"Begining point is:";
                                     begin.Display();
                          cout<<"End Point is:";
                                     end.Display();
             }
             static Line* CreateLine(unsigned int id, Point a, Point b)
             {
                          return new Line(id,a,b);
             }

           virtual ~Line(){}
private:
           Point begin;
           Point end;
};
A leaf class – rectangle – a final class as well
class Rectangle : public Shape
{
private:
            //private constructor
            Rectangle(unsigned int id, Point& p, int width, int height)
            {
                          top_left = p;
                          top_right = Point(p.X_COORD() + width, p.Y_COORD());
                          bottom_left = Point(p.X_COORD() , p.Y_COORD() + height);
                          bottom_right = Point(p.X_COORD() + width, p.Y_COORD() + height);
                          resource_id = id;
                          Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this));
            }
            //private copy constructor
            Rectangle(const Rectangle& in){ }
                          //private assignment operator
            Rectangle& operator=(const Rectangle& in) { }
public:
            static Rectangle* CreateRectange(unsigned int id, Point& p, int width, int height)
            {
                          return new Rectangle(id, p, width, height);

            }
            virtual ~Rectangle(){}
            virtual void Display()
            {
                          cout<<"The four vertices are:"<<endl;
                          cout<<"Top Left :" ;
                                      top_left.Display();
                          cout <<"Top Right :";
                                      top_right.Display();
                          cout<<"Bottom Left :";
                                      bottom_left.Display();
                          cout<<"Bottom Right :";
                                      bottom_right.Display();

            }

            //Attributes
private:
            Point top_left;
            Point top_right;
            Point bottom_left;
            Point bottom_right;
};
A composite class - picture
class Picture : public Shape
{
public:
           Picture(unsigned int id)
           {
                       resource_id = id;
                       Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this));
           }
           virtual void Display()
           {
                       vector<Shape*>::iterator p = Components.begin();
                       while (p != Components.end())
                       {
                                   (*p)->Display();
                                   p++;
                       }
           }

          //Adds the component with the resource id equal to the passed parameter
          virtual void Add (unsigned int id)
          {
                      Shape* s = FindItem(id);

                    Components.push_back(s);

                    s->SetParentOfComponent(this);

          }
Class Picture ... contd...
//removes the component from the list with the resource_id equal
to the parameter passed
      virtual void Remove(unsigned int id)
      {
            Shape* s = FindItem(id);
            vector<Shape*>::iterator p = Components.begin();
            int pos = 0;
            while (p != Components.end())
            {
                  if(Components.at(pos) == s)
                        break;
                  pos++;
                  p++;
            }
            Components.erase(p);
            s->SetParentOfComponent(NULL);
      }
Class Picture ... contd...
//will return the chile having the id equal to the passed value.
           virtual Shape* GetChild (unsigned int id)
           {
                     return FindItem(id);
           }


           virtual ~Picture()
           {
                     vector<Shape*>::iterator p = Components.begin();

                   int pos = 0;
                   while (p != Components.end())
                   {
                             delete(Components.at(pos));
                             p++;
                             pos++;
                   }


                   Components.clear();
           }
private:
           vector<Shape*> Components;
};
void main()
                                         The client - main()
{
              Point p1(10,20);
              Point p2(30,40);
              Point p3(50,60);
              Point p4(70,80);
              Point p5(100,110);
              Point p6(150,200);
              Line* l1 = Line::CreateLine(ID_LINE1,p1,p2);
              try
              {
              l1->Add(0);
              }
              catch(LeafClassTypeException& e)
              {
                            e.printerrormsg();
              }
              Line* l2 = Line::CreateLine(ID_LINE2,p3,p4);
              Line* l3 = Line::CreateLine(ID_LINE3,p5,p6);

              Rectangle* r1 = Rectangle::CreateRectange(ID_RECTANGLE1, p1, 50,25);


              Shape* p = new Picture(ID_PICTURE);
              p->Add(ID_LINE1);
              p->Add(ID_LINE2);
              p->Add(ID_LINE3);
              p->Add(ID_RECTANGLE1);

              (p->GetChild(ID_RECTANGLE1))->Display();

              p->Remove(ID_RECTANGLE1);

              p->Display();

              cout<<p<<endl;

              cout<<l1->GetParentOfComponent()<<endl;

              delete p;

}
The helper exception class


class LeafClassTypeException
{
public:
     void printerrormsg()
     {
          cout<<"This is a leaf class"<<endl;
     }
}
;
Implementation Details


 Every component is identifiable through its
resource id

 Whenever we create an object (leaf or composite
object), it creates a key pair of the id and the
pointer to that object and pushes this key into a
MAP, from which we can easily search for that
component in later times through its resource id
Implementation details




 The leaf classes, namely Line and Rectangle
have been implemented as final classes by
making their constructors, copy constructors and
assignment operators private and providing static
member functions to create them.
Issues


 GetParentofComponent can be used to traverse
the tree hierarchy

 We have to make sure that any child can have a
composite object as its parent

    No child can have another child if its a leaf

 Whenever a leaf class tries to add a child it
throws the LeafClassException
Issues



 Add and Remove functions have been defined in
the Root class.

    For the leaf classes these just throw exceptions

 However it helps the client to treat leaf and
composite objects uniformly

More Related Content

What's hot

Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functionsPrincess Sam
 
Evolutionary Problems In Aspect Oriented Software Development
Evolutionary Problems In Aspect Oriented Software DevelopmentEvolutionary Problems In Aspect Oriented Software Development
Evolutionary Problems In Aspect Oriented Software Developmentkim.mens
 
Max Koretskyi "Why are Angular and React so fast?"
Max Koretskyi "Why are Angular and React so fast?"Max Koretskyi "Why are Angular and React so fast?"
Max Koretskyi "Why are Angular and React so fast?"Fwdays
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Aman Deep
 
Type level programming in Scala
Type level programming in ScalaType level programming in Scala
Type level programming in ScalaIkhoon Eom
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++vidyamittal
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 

What's hot (20)

Pointers
PointersPointers
Pointers
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
 
OpenGL ES 3 Reference Card
OpenGL ES 3 Reference CardOpenGL ES 3 Reference Card
OpenGL ES 3 Reference Card
 
Evolutionary Problems In Aspect Oriented Software Development
Evolutionary Problems In Aspect Oriented Software DevelopmentEvolutionary Problems In Aspect Oriented Software Development
Evolutionary Problems In Aspect Oriented Software Development
 
Pre zen ta sion
Pre zen ta sionPre zen ta sion
Pre zen ta sion
 
The STL
The STLThe STL
The STL
 
OpenXR 1.0 Reference Guide
OpenXR 1.0 Reference GuideOpenXR 1.0 Reference Guide
OpenXR 1.0 Reference Guide
 
Max Koretskyi "Why are Angular and React so fast?"
Max Koretskyi "Why are Angular and React so fast?"Max Koretskyi "Why are Angular and React so fast?"
Max Koretskyi "Why are Angular and React so fast?"
 
OpenGL ES 3.1 Reference Card
OpenGL ES 3.1 Reference CardOpenGL ES 3.1 Reference Card
OpenGL ES 3.1 Reference Card
 
glTF 2.0 Reference Guide
glTF 2.0 Reference GuideglTF 2.0 Reference Guide
glTF 2.0 Reference Guide
 
OpenGL 4.4 Reference Card
OpenGL 4.4 Reference CardOpenGL 4.4 Reference Card
OpenGL 4.4 Reference Card
 
Supstat nyc subway
Supstat nyc subwaySupstat nyc subway
Supstat nyc subway
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
 
Type level programming in Scala
Type level programming in ScalaType level programming in Scala
Type level programming in Scala
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
 
Collection v3
Collection v3Collection v3
Collection v3
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
ECMA 入门
ECMA 入门ECMA 入门
ECMA 入门
 

Viewers also liked

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

Viewers also liked (7)

Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
 
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 Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design 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

OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptSaadAsim11
 
Can you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdfCan you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdfFashionBoutiquedelhi
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
Hi, Please find mu codeimport java.util.Random;public class Sup.pdf
Hi, Please find mu codeimport java.util.Random;public class Sup.pdfHi, Please find mu codeimport java.util.Random;public class Sup.pdf
Hi, Please find mu codeimport java.util.Random;public class Sup.pdfkaran8801
 
This C++ program keeps giving me the wrong median. #include ios.pdf
This C++ program keeps giving me the wrong median. #include ios.pdfThis C++ program keeps giving me the wrong median. #include ios.pdf
This C++ program keeps giving me the wrong median. #include ios.pdfpreetineeteshhiwrale
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
namespace ConsoleApplication15 { class Program { static void Main(stri.docx
namespace ConsoleApplication15 { class Program { static void Main(stri.docxnamespace ConsoleApplication15 { class Program { static void Main(stri.docx
namespace ConsoleApplication15 { class Program { static void Main(stri.docxmaximapikvu8
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montageKris Kowal
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
 
Inheritance compiler support
Inheritance compiler supportInheritance compiler support
Inheritance compiler supportSyed Zaid Irshad
 
could you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdfcould you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdfferoz544
 

Similar to Composite Pattern (20)

C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
oop objects_classes
oop objects_classesoop objects_classes
oop objects_classes
 
Opp compile
Opp compileOpp compile
Opp compile
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Can you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdfCan you please debug this Thank you in advance! This program is sup.pdf
Can you please debug this Thank you in advance! This program is sup.pdf
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Hi, Please find mu codeimport java.util.Random;public class Sup.pdf
Hi, Please find mu codeimport java.util.Random;public class Sup.pdfHi, Please find mu codeimport java.util.Random;public class Sup.pdf
Hi, Please find mu codeimport java.util.Random;public class Sup.pdf
 
662305 10
662305 10662305 10
662305 10
 
Day 1
Day 1Day 1
Day 1
 
C++ programs
C++ programsC++ programs
C++ programs
 
This C++ program keeps giving me the wrong median. #include ios.pdf
This C++ program keeps giving me the wrong median. #include ios.pdfThis C++ program keeps giving me the wrong median. #include ios.pdf
This C++ program keeps giving me the wrong median. #include ios.pdf
 
Cquestions
Cquestions Cquestions
Cquestions
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
namespace ConsoleApplication15 { class Program { static void Main(stri.docx
namespace ConsoleApplication15 { class Program { static void Main(stri.docxnamespace ConsoleApplication15 { class Program { static void Main(stri.docx
namespace ConsoleApplication15 { class Program { static void Main(stri.docx
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
Inheritance compiler support
Inheritance compiler supportInheritance compiler support
Inheritance compiler support
 
Applications
ApplicationsApplications
Applications
 
could you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdfcould you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdf
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
 

More from Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trieSomenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidSomenath Mukhopadhyay
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsSomenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docsSomenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidSomenath Mukhopadhyay
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in JavaSomenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsSomenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureSomenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternSomenath Mukhopadhyay
 

More from Somenath Mukhopadhyay (20)

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Uml training
Uml trainingUml training
Uml training
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Composite Pattern

  • 1. Composite Pattern by Somenath Mukhopadhyay som@som-itsolutions.com
  • 2. Structural pattern  Compose objects into a tree structure to represent part-whole relationship
  • 3.  An abstract class represents both primitives and containers  The client handles both the primitives and their containers in the same fashion
  • 4. Tree structure of the Composite Pattern
  • 5. Applicability  To represent part-whole hierarchy  To make the client ignorant about whether it is interacting with an individual object or a composite object
  • 7. Example – base class Shape class Shape { public: Shape(){} virtual void Add(unsigned int id) { throw LeafClassTypeException(); }; virtual void Remove(unsigned int id){}; //leaf classes will not override it..however, it will be overridden by the composite class. virtual Shape* GetChild(unsigned int id) { throw LeafClassTypeException(); }; //Using this reference the "Chain of Responsibility" can be implemented virtual Shape* GetParentOfComponent() { return ParentOfComponent; }; virtual void SetParentOfComponent(Shape* s) { ParentOfComponent = s; } virtual void Display(){}; virtual Shape* FindItem(unsigned int id); //implementation afterwards virtual ~Shape(){}; protected: Shape* ParentOfComponent; unsigned int resource_id; };
  • 8. Iterator and the FindItem function typedef map <unsigned int, Shape*, less<unsigned int> > theMap; theMap Resource_Map; theMap::iterator theIterator; Shape* Shape::FindItem(unsigned int id) { theIterator = Resource_Map.begin(); while (theIterator != Resource_Map.end()) { theIterator = Resource_Map.find(id); Shape* s = (*theIterator).second; theIterator++; return s; } return NULL; }
  • 9. A leaf class - Point class Point : public Shape { public: Point():x_Coord(0),y_Coord(0){} Point(int x, int y):x_Coord(x), y_Coord(y){} Point(const Point& p) { x_Coord = p.x_Coord; y_Coord = p.y_Coord; } Point& operator = (const Point& p) { x_Coord = p.x_Coord; y_Coord = p.y_Coord; return *this; } virtual void Display() { cout<<"X Coordinate is:"<<x_Coord<<endl; cout<<"Y Coordinate is:"<<y_Coord<<endl; } int X_COORD() { return x_Coord; } int Y_COORD() { return y_Coord; } virtual ~Point(){} private: int x_Coord; int y_Coord; };
  • 10. A leaf class – line – a final class as well //class Line is working as a leaf class.. Lets implement it as a final class class Line : public Shape { private: //private constructor Line(unsigned int id):begin(0,0),end(0,0) { resource_id = id; Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this)); } //private constructor Line(unsigned int id, Point a, Point b):begin(a),end(b) { resource_id = id; Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this)); } //private copy constructor Line(const Line& in){ } //private assignment operator Line& operator=(const Line& in){ } public: virtual void Display() { cout<<"Begining point is:"; begin.Display(); cout<<"End Point is:"; end.Display(); } static Line* CreateLine(unsigned int id, Point a, Point b) { return new Line(id,a,b); } virtual ~Line(){} private: Point begin; Point end; };
  • 11. A leaf class – rectangle – a final class as well class Rectangle : public Shape { private: //private constructor Rectangle(unsigned int id, Point& p, int width, int height) { top_left = p; top_right = Point(p.X_COORD() + width, p.Y_COORD()); bottom_left = Point(p.X_COORD() , p.Y_COORD() + height); bottom_right = Point(p.X_COORD() + width, p.Y_COORD() + height); resource_id = id; Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this)); } //private copy constructor Rectangle(const Rectangle& in){ } //private assignment operator Rectangle& operator=(const Rectangle& in) { } public: static Rectangle* CreateRectange(unsigned int id, Point& p, int width, int height) { return new Rectangle(id, p, width, height); } virtual ~Rectangle(){} virtual void Display() { cout<<"The four vertices are:"<<endl; cout<<"Top Left :" ; top_left.Display(); cout <<"Top Right :"; top_right.Display(); cout<<"Bottom Left :"; bottom_left.Display(); cout<<"Bottom Right :"; bottom_right.Display(); } //Attributes private: Point top_left; Point top_right; Point bottom_left; Point bottom_right; };
  • 12. A composite class - picture class Picture : public Shape { public: Picture(unsigned int id) { resource_id = id; Resource_Map.insert(theMap::value_type(resource_id,(Shape*)this)); } virtual void Display() { vector<Shape*>::iterator p = Components.begin(); while (p != Components.end()) { (*p)->Display(); p++; } } //Adds the component with the resource id equal to the passed parameter virtual void Add (unsigned int id) { Shape* s = FindItem(id); Components.push_back(s); s->SetParentOfComponent(this); }
  • 13. Class Picture ... contd... //removes the component from the list with the resource_id equal to the parameter passed virtual void Remove(unsigned int id) { Shape* s = FindItem(id); vector<Shape*>::iterator p = Components.begin(); int pos = 0; while (p != Components.end()) { if(Components.at(pos) == s) break; pos++; p++; } Components.erase(p); s->SetParentOfComponent(NULL); }
  • 14. Class Picture ... contd... //will return the chile having the id equal to the passed value. virtual Shape* GetChild (unsigned int id) { return FindItem(id); } virtual ~Picture() { vector<Shape*>::iterator p = Components.begin(); int pos = 0; while (p != Components.end()) { delete(Components.at(pos)); p++; pos++; } Components.clear(); } private: vector<Shape*> Components; };
  • 15. void main() The client - main() { Point p1(10,20); Point p2(30,40); Point p3(50,60); Point p4(70,80); Point p5(100,110); Point p6(150,200); Line* l1 = Line::CreateLine(ID_LINE1,p1,p2); try { l1->Add(0); } catch(LeafClassTypeException& e) { e.printerrormsg(); } Line* l2 = Line::CreateLine(ID_LINE2,p3,p4); Line* l3 = Line::CreateLine(ID_LINE3,p5,p6); Rectangle* r1 = Rectangle::CreateRectange(ID_RECTANGLE1, p1, 50,25); Shape* p = new Picture(ID_PICTURE); p->Add(ID_LINE1); p->Add(ID_LINE2); p->Add(ID_LINE3); p->Add(ID_RECTANGLE1); (p->GetChild(ID_RECTANGLE1))->Display(); p->Remove(ID_RECTANGLE1); p->Display(); cout<<p<<endl; cout<<l1->GetParentOfComponent()<<endl; delete p; }
  • 16. The helper exception class class LeafClassTypeException { public: void printerrormsg() { cout<<"This is a leaf class"<<endl; } } ;
  • 17. Implementation Details  Every component is identifiable through its resource id  Whenever we create an object (leaf or composite object), it creates a key pair of the id and the pointer to that object and pushes this key into a MAP, from which we can easily search for that component in later times through its resource id
  • 18. Implementation details  The leaf classes, namely Line and Rectangle have been implemented as final classes by making their constructors, copy constructors and assignment operators private and providing static member functions to create them.
  • 19. Issues  GetParentofComponent can be used to traverse the tree hierarchy  We have to make sure that any child can have a composite object as its parent  No child can have another child if its a leaf  Whenever a leaf class tries to add a child it throws the LeafClassException
  • 20. Issues  Add and Remove functions have been defined in the Root class.  For the leaf classes these just throw exceptions  However it helps the client to treat leaf and composite objects uniformly