SlideShare ist ein Scribd-Unternehmen logo
1 von 12
1




Design Pattern –
Composite
Presented by Joncash
4/13/2012
2




Outline
•   Definition
•   Motivation
•   When to Use
•   Structure
•   Application
•   Example
3




Definition
• The composite pattern describes that a group of
  objects are to be treated in the same way as a
  single instance of an object.
• The intent of a composite is to "compose" objects
  into tree structures to represent part-whole
  hierarchies.
4




Motivation
• When dealing with tree-structured data,
  programmers often have to discriminate
  between a leaf-node and a branch. This makes
  code more complex, and therefore, error prone.
5




When to Use
• If programmers find that they are using multiple
  objects in the same way, and often have nearly
  identical code to handle each of them, then
  composite is a good choice
6




Structure
7




Classic Composite application
• ASP.NET
 ▫ TreeView
 ▫ System.Web.UI.Control
8




Example
static void Main()                 // Add and remove a leaf
{                                     Leaf leaf = new Leaf("Leaf D");
   // Create a tree structure         root.Add(leaf);
   Composite root = new               root.Remove(leaf);
   Composite("root");
   root.Add(new Leaf("Leaf A"));   // Recursively display tree
   root.Add(new Leaf("Leaf B"));      root.Display(1);

  Composite comp = new             // Wait for user
  Composite("Composite X");           Console.ReadKey();
  comp.Add(new Leaf("Leaf XA"));
  comp.Add(new Leaf("Leaf XB"));   }
   root.Add(comp);
   root.Add(new Leaf("Leaf C"));
9




Component
abstract class Component
{
  protected string name;
    // Constructor
    public Component(string name)
    {
      this.name = name;
    }
    public abstract void Add(Component c);
    public abstract void Remove(Component c);
    public abstract void Display(int depth);
}
10




Composite
class Composite : Component
{                                 public override void Remove(Component com
  private List<Component>          ponent)
  _children                       {
  = new List<Component>();          _children.Remove(component);
                                  }
 // Constructor
 public Composite(string name)    public override void Display(int depth)
   : base(name)                   {
 {                                  Console.WriteLine(new String('-', depth) +
 }                                 name);

public override void Add(Compon    // Recursively display child nodes
  ent component)                   foreach (Component component in _children
 {                                )
   _children.Add(component);       {
 }                                   component.Display(depth + 2);
                                   }
                                  }
11




Leaf
class Leaf : Component       public override void Add(Component c)
{                             {
  // Constructor                Console.WriteLine("Cannot add to a
  public Leaf(string name)    leaf");
    : base(name)              }
  {
  }                           public override void Remove(Component c)
                              {
                                Console.WriteLine("Cannot remove from
                              a leaf");
                              }

                              public override void Display(int depth)
                              {
                                Console.WriteLine(new String('-', depth) +
                              name);
                              }
12




Reference
• wiki/Composite_pattern
• dofactory.com/Patterns/PatternComposite

Weitere ähnliche Inhalte

Was ist angesagt?

M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
Dang Tuan
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
Raj Chanchal
 

Was ist angesagt? (20)

Composite design pattern
Composite design patternComposite design pattern
Composite design pattern
 
Concept of Object Oriented Programming
Concept of Object Oriented Programming Concept of Object Oriented Programming
Concept of Object Oriented Programming
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
encapsulation
encapsulationencapsulation
encapsulation
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
PATTERNS03 - Behavioural Design Patterns
PATTERNS03 - Behavioural Design PatternsPATTERNS03 - Behavioural Design Patterns
PATTERNS03 - Behavioural Design Patterns
 
Mediator
MediatorMediator
Mediator
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
Object database standards, languages and design
Object database standards, languages and designObject database standards, languages and design
Object database standards, languages and design
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Oops slide
Oops slide Oops slide
Oops slide
 
ch6
ch6ch6
ch6
 
Ashish oot
Ashish ootAshish oot
Ashish oot
 

Andere mochten auch

Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013
Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013
Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013
FEDERICO ALMENARA CHECA
 
Cuadernillo v termodinamica
Cuadernillo v termodinamicaCuadernillo v termodinamica
Cuadernillo v termodinamica
ivan_antrax
 
Zeeshan Khan 2016 Cv 2
Zeeshan Khan 2016 Cv 2Zeeshan Khan 2016 Cv 2
Zeeshan Khan 2016 Cv 2
Zeeshan Khan
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution Report
Fridz Felisco
 

Andere mochten auch (14)

Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013
Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013
Guíon Eucaristía. Domingo XXIX del To. 20 de octubre del 2013
 
Unleash Your Potential! Successfully Navigate Your Way through Global and Vir...
Unleash Your Potential! Successfully Navigate Your Way through Global and Vir...Unleash Your Potential! Successfully Navigate Your Way through Global and Vir...
Unleash Your Potential! Successfully Navigate Your Way through Global and Vir...
 
CCP_SM
CCP_SMCCP_SM
CCP_SM
 
DemoFest 2015 "Mission—JHome Content Manager"
DemoFest 2015 "Mission—JHome Content Manager"DemoFest 2015 "Mission—JHome Content Manager"
DemoFest 2015 "Mission—JHome Content Manager"
 
Cuadernillo v termodinamica
Cuadernillo v termodinamicaCuadernillo v termodinamica
Cuadernillo v termodinamica
 
Diario Resumen 20150821
Diario Resumen 20150821Diario Resumen 20150821
Diario Resumen 20150821
 
Zeeshan Khan 2016 Cv 2
Zeeshan Khan 2016 Cv 2Zeeshan Khan 2016 Cv 2
Zeeshan Khan 2016 Cv 2
 
ALBY 1
ALBY 1ALBY 1
ALBY 1
 
Termodinamica trabajo resumen-ejercicios
Termodinamica trabajo  resumen-ejerciciosTermodinamica trabajo  resumen-ejercicios
Termodinamica trabajo resumen-ejercicios
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution Report
 
Chave hh plastica v0 serie FK 233
Chave hh plastica v0 serie FK 233Chave hh plastica v0 serie FK 233
Chave hh plastica v0 serie FK 233
 
curl_multi_exec()でFire-and-forgetに失敗した話
curl_multi_exec()でFire-and-forgetに失敗した話curl_multi_exec()でFire-and-forgetに失敗した話
curl_multi_exec()でFire-and-forgetに失敗した話
 
El país de jesús
El país de jesúsEl país de jesús
El país de jesús
 
La ladrona de libros ficha didáctica
La ladrona de libros ficha didácticaLa ladrona de libros ficha didáctica
La ladrona de libros ficha didáctica
 

Ähnlich wie Design pattern composite 20120413 joncash 01

Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
srmelody
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 

Ähnlich wie Design pattern composite 20120413 joncash 01 (20)

data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Clean Code
Clean CodeClean Code
Clean Code
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Object
ObjectObject
Object
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Building maintainable web apps with Angular MS TechDays 2017
Building maintainable web apps with Angular MS TechDays 2017Building maintainable web apps with Angular MS TechDays 2017
Building maintainable web apps with Angular MS TechDays 2017
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Oops recap
Oops recapOops recap
Oops recap
 

Mehr von LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdf
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 

Design pattern composite 20120413 joncash 01

  • 2. 2 Outline • Definition • Motivation • When to Use • Structure • Application • Example
  • 3. 3 Definition • The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. • The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies.
  • 4. 4 Motivation • When dealing with tree-structured data, programmers often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, error prone.
  • 5. 5 When to Use • If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice
  • 7. 7 Classic Composite application • ASP.NET ▫ TreeView ▫ System.Web.UI.Control
  • 8. 8 Example static void Main() // Add and remove a leaf { Leaf leaf = new Leaf("Leaf D"); // Create a tree structure root.Add(leaf); Composite root = new root.Remove(leaf); Composite("root"); root.Add(new Leaf("Leaf A")); // Recursively display tree root.Add(new Leaf("Leaf B")); root.Display(1); Composite comp = new // Wait for user Composite("Composite X"); Console.ReadKey(); comp.Add(new Leaf("Leaf XA")); comp.Add(new Leaf("Leaf XB")); } root.Add(comp); root.Add(new Leaf("Leaf C"));
  • 9. 9 Component abstract class Component { protected string name; // Constructor public Component(string name) { this.name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void Display(int depth); }
  • 10. 10 Composite class Composite : Component { public override void Remove(Component com private List<Component> ponent) _children { = new List<Component>(); _children.Remove(component); } // Constructor public Composite(string name) public override void Display(int depth) : base(name) { { Console.WriteLine(new String('-', depth) + } name); public override void Add(Compon // Recursively display child nodes ent component) foreach (Component component in _children { ) _children.Add(component); { } component.Display(depth + 2); } }
  • 11. 11 Leaf class Leaf : Component public override void Add(Component c) { { // Constructor Console.WriteLine("Cannot add to a public Leaf(string name) leaf"); : base(name) } { } public override void Remove(Component c) { Console.WriteLine("Cannot remove from a leaf"); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); }

Hinweis der Redaktion

  1. Implementing the composite pattern lets clients treat individual objects and compositions uniformly 組合模式 : 將物件組合成樹形結再以表示「部份 - 整體」的層次結構 組合模式使得用戶對單個物件和組合物件的使用具有一致性。
  2. Composite can be used when clients should ignore the difference between compositions of objects and individual objects.