SlideShare a Scribd company logo
1 of 21
Download to read offline
Encapsulate Composite
     with Builder
       Gian Lorenzetto
Recap ...

• Replace Implicit Tree with Composite
  (Refactoring to Patterns)
• Refactoring to Composite loosens
  coupling to implicit tree
• Builder loosens coupling to Composite
Builder (Gof)
BuilderDiagram_1196754930587
Builder (GoF)
•   The construction of a complex object is separated from its
    representation so that the same construction process can create
    different representations

•   Builder Defines the required operations for creating various parts of
    a product

•   ConcreteBuilder Implements the operations declared in the Builder
    interface.

•   Director Builds a specific product via the interface exposed by the
    Builder object.

•   Product The concrete type the Builder object creates.
Class Diagram 1_1196587101774




                                                      TagNode activityTag = new TagNode(“activity”);
                                                         ...
                                                         TagNode flavorsTag = new TagNode(“flavors”);
                                                         activityTag.add(favorsTag);
                                                             ...
                                                             TagNode flavorTag = new TagNode(“flavor”);
                                                             flavorsTag.add(flavorTag);
Class Diagram 3_1196677789548




                                                          TagBuilder builder = new TagBuilder(“activity”);
                                                          ...
                                                              builder.addChild(“flavors”);
                                                              ...
                                                                  builder.addToParent(“flavors”, “flavor”);
                                                                  ...
Class Diagram 2_1196596929958




                                        Document doc = new DocumentImpl();
                                        Element orderTag = doc.createElement(“order”);
                                        orderTag.setAttribute(“id”, order.getOrderId());
                                        Element productTag = doc.createElement(“product”);
                                        productTag.setAttribute(“id”, product.getID());
                                        Text productName = doc.createTextNode(product.getName());
                                        productTag.appendChild(productName);
                                        orderTag.appendChld(productTag);




Class Diagram 4_1196679481681




                                               DOMBuilder orderBuilder = new DOMBuilder(“order”)
                                               orderBuilder.addAttribute(“id”, order.getOrder());
                                               orderBuilder.addChild(“product”);
                                               orderBuilder.addAttribute(“id”, product.getID());
                                               orderBuilder.adValue(product.getName());
•   Benefits
       Simplifies a client’s code for constructing a Composite
       Reduces the repetitive and error-prone nature of
       Composite creation
       Creates a loose coupling between client and
       Composite
       Allows for different representations of the
       encapsulated Composite or complex object

•   Liabilities
       May not have the most intention-revealing interface
Mechanics
1. Create Builder
2. Make Builder capable of creating children
3. Make Builder capable of setting attributes
   on nodes
4. Reflect on interface ... simplify
5. Refactor Composite construction code to
   use Builder
TagNode Revisited
         Class Diagram 5_1196681761272




                                         *




Composite interface ~ Builder interface
Step 1.
                                  Create Builder


public class TagBuilderTest ...

   public void testBuilderOneNode()
   {
      String expectedXml = “<flavors/>”;
      String actualXml = TagBuilder(“flavors”).toXml();

       assertXmlEquals(expectedXml, actualXml);
   }
Step 1.
                 Create Builder

public class TagBuilder
{
   private TagNode rootNode;

    public TagBuilder(String rootTagName)
    {
       rootNode = new TagNode(rootTagName);
    }

    public String toXml()
    {
       return rootNode.toString();
    }
}
Step 2.
       Support child creation and placement

public class TagBuilderTest ...

   public void testBuilderOneChild()
   {
      String expectedXml = “<flavors>” +
                               “<flavor/>” +
                            “</flavors>”;

        TagBuilder builder = TagBuilder(“flavors”);
        builder.addChild(“flavor”);
        String actualXml = builder.toXml();

        assertXmlEquals(expectedXml, actualXml);
   }
Step 2.
Support child creation and placement
    public class TagBuilder
    {
       private TagNode rootNode;
       private TagNode currentNode;

      public TagBuilder(String rootTagName)
      {
         rootNode = new TagNode(rootTagName);
         currentNode = rootNode;
      }

      pubic void addChild(String childTagName)
      {
        TagNode parentNode = currentNode;
        currentNode = new TagNode(childTagName);
        parentNode.addChild(curentNode);
      }

      ...
Step 2.
   Support child creation and placement

public class TagBuilderTest ...

   public void testBuilderOneChild()
   {
      String expectedXml = “<flavors>” +
                               “<flavor1/>” +
                               “<flavor2/>” +
                            “</flavors>”;

       TagBuilder builder = TagBuilder(“flavors”);
       builder.addChild(“flavor1”);
       builder.addSibling(“flavor2”);
       String actualXml = builder.toXml();

       assertXmlEquals(expectedXml, actualXml);
   }
Step 2.
Support child creation and placement
  public class TagBuilder ...

     pubic void addChild(String childTagName)
     {
        addTo(currentNode, childTagName);
     }

     public void addSibling(String siblingTagName)
     {
       addTo(currentNode.getParent(), siblingTagName);
     }

     private void addTo(TagNode parentNode, String tagName)
     {
         currentNode = new TagNode(tagName);
         parentNode.addChild(curentNode);
     }
     ...


    1. Refactor Composite to support Builder
    2. Thirdparty Composite?
Step 3.
             Support attributes and values
public class TagBuilderTest ...
   public void testAttributesAndVaues()
   {
       String expectedXml = “<flavor name=ʼTest-Driven Developmentʼ>” +
                                 “<requirements>” +
                                    “<requirement type=ʼhardwareʼ>” +
                                       “1 computer for every 2 participants” +
                                    “</requirement>”
                                 “</requirements>” +
                              “</flavor>”;

       TagBuilder builder = TagBuilder(“flavor”);
       builder.addAttribute(“name”, “Test-Driven Development”);
       builder.addChild(“requirements”);
       builder.addToParent(“requirements”, “requirement”);
       builder.addAttribute(“type”, “hardware”);
       builder.addValue(“1 computer for every 2 participants”);
       String actualXml = builder.toXml();

       assertXmlEquals(expectedXml, actualXml);
   }
Step 3.
     Support attributes and values


public class TagBuilder ...

   pubic void addAttribute(String name, String value)
   {
     currentNode.addAttribute(name, value);
   }

   public void addValue(String value)
   {
     currentNode.addValue(value);
   }

   ...
Step 4.
                                    Reflect ...

public class TagBuilder
{
   public TagBuilder(String rootTagName) { ... }

    public void addChild(String childTagName) { ... }
    public void addSibling(String siblingTagName) { ... }
    public void addToParent(String parentTagName, String childTagName) { ... }

    public void addAttribute(String name, String value) { ... }
    public void addValue(String value) { ... }

    public String toXml() { ... }
}
public class TagBuilder
{
   public TagBuilder(String rootTagName) { ... }

    public void addChild(String childTagName) { ... }
    public void addSibling(String siblingTagName) { ... }
    public void addToParent(String parentTagName, String childTagName) { ... }

    public void addAttribute(String name, String value);
    public void addValue(String value);

    public String toXml() { ... }
}




public class TagNode
{
   public TagNode(String tagName) { ... }

    public void add(TagNode childNode) { ... }

    public void addAttribute(String name, String value) { ... }
    public void addValue(String value) { ... }

    public String toString() { ... }
}
Step 5.
Replace Composite construction code
public class CatalogWriter ...

   TagNode requirementsTag = new TagNode(“requirements”);
   flavorTag.add(requirementsTag);
   for (int i = 0; i < requirementsCount; ++i)
   {
       Requirement requirement = flavor.getRequirements()[i];
       TagNode requirementTag = new TagNode(“requirement”);
       ...
       requirementsTag.add(requirementsTag);
   }

public class CatalogWriter ...

   builder.addChild(“requirements”);
   for (int i = 0; i < requirementsCount; ++i)
   {
       Requirement requirement = flavor.getRequirements()[i];
       builder.addToParent(“requirements”, “requirement”);
       ...
   }
Questions?

More Related Content

What's hot

Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF BindingsEuegene Fedorenko
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)Yurii Kotov
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил АнохинFwdays
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Fwdays
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightMichael Pustovit
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutDror Helper
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 
GQL CheatSheet 1.1
GQL CheatSheet 1.1GQL CheatSheet 1.1
GQL CheatSheet 1.1sones GmbH
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
JavaFX for Business Application Developers
JavaFX for Business Application DevelopersJavaFX for Business Application Developers
JavaFX for Business Application DevelopersMichael Heinrichs
 
Data binding в массы!
Data binding в массы!Data binding в массы!
Data binding в массы!Artjoker
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
GQL cheat sheet latest
GQL cheat sheet latestGQL cheat sheet latest
GQL cheat sheet latestsones GmbH
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkKaniska Mandal
 

What's hot (20)

Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF Bindings
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
guice-servlet
guice-servletguice-servlet
guice-servlet
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"
 
Specs2
Specs2Specs2
Specs2
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 light
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 
GQL CheatSheet 1.1
GQL CheatSheet 1.1GQL CheatSheet 1.1
GQL CheatSheet 1.1
 
Con5623 pdf 5623_001
Con5623 pdf 5623_001Con5623 pdf 5623_001
Con5623 pdf 5623_001
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Clean Test Code
Clean Test CodeClean Test Code
Clean Test Code
 
JavaFX for Business Application Developers
JavaFX for Business Application DevelopersJavaFX for Business Application Developers
JavaFX for Business Application Developers
 
Data binding в массы!
Data binding в массы!Data binding в массы!
Data binding в массы!
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
GQL cheat sheet latest
GQL cheat sheet latestGQL cheat sheet latest
GQL cheat sheet latest
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
 

Similar to Mpg Dec07 Gian Lorenzetto

Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in productionMartijn Dashorst
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptmartinlippert
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片cfc
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Web Components Everywhere
Web Components EverywhereWeb Components Everywhere
Web Components EverywhereIlia Idakiev
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profitNikolas Vourlakis
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Python Ireland
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKMax Pronko
 
Building Grails Plugins - Tips And Tricks
Building Grails Plugins - Tips And TricksBuilding Grails Plugins - Tips And Tricks
Building Grails Plugins - Tips And TricksMike Hugo
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserHoward Lewis Ship
 
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxOrdering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxhopeaustin33688
 
Practical Experience Building JavaFX Rich Clients
Practical Experience Building JavaFX Rich ClientsPractical Experience Building JavaFX Rich Clients
Practical Experience Building JavaFX Rich ClientsRichard Bair
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 

Similar to Mpg Dec07 Gian Lorenzetto (20)

Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScript
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Web Components Everywhere
Web Components EverywhereWeb Components Everywhere
Web Components Everywhere
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
#JavaFX.forReal()
#JavaFX.forReal()#JavaFX.forReal()
#JavaFX.forReal()
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profit
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
 
Building Grails Plugins - Tips And Tricks
Building Grails Plugins - Tips And TricksBuilding Grails Plugins - Tips And Tricks
Building Grails Plugins - Tips And Tricks
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxOrdering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
 
Practical Experience Building JavaFX Rich Clients
Practical Experience Building JavaFX Rich ClientsPractical Experience Building JavaFX Rich Clients
Practical Experience Building JavaFX Rich Clients
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 

More from melbournepatterns (20)

An Introduction to
An Introduction to An Introduction to
An Introduction to
 
State Pattern from GoF
State Pattern from GoFState Pattern from GoF
State Pattern from GoF
 
Iterator Pattern
Iterator PatternIterator Pattern
Iterator Pattern
 
Iterator
IteratorIterator
Iterator
 
Concurrency Patterns
Concurrency PatternsConcurrency Patterns
Concurrency Patterns
 
Continuous Integration, Fast Builds and Flot
Continuous Integration, Fast Builds and FlotContinuous Integration, Fast Builds and Flot
Continuous Integration, Fast Builds and Flot
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Code Contracts API In .Net
Code Contracts API In .NetCode Contracts API In .Net
Code Contracts API In .Net
 
LINQ/PLINQ
LINQ/PLINQLINQ/PLINQ
LINQ/PLINQ
 
Gpu Cuda
Gpu CudaGpu Cuda
Gpu Cuda
 
Facade Pattern
Facade PatternFacade Pattern
Facade Pattern
 
Phani Kumar - Decorator Pattern
Phani Kumar - Decorator PatternPhani Kumar - Decorator Pattern
Phani Kumar - Decorator Pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Prototype Design Pattern
Prototype Design PatternPrototype Design Pattern
Prototype Design Pattern
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
 
Abstract Factory Design Pattern
Abstract Factory Design PatternAbstract Factory Design Pattern
Abstract Factory Design Pattern
 
A Little Lisp
A Little LispA Little Lisp
A Little Lisp
 
State Pattern in Flex
State Pattern in FlexState Pattern in Flex
State Pattern in Flex
 
Active Object
Active ObjectActive Object
Active Object
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

Mpg Dec07 Gian Lorenzetto

  • 1. Encapsulate Composite with Builder Gian Lorenzetto
  • 2. Recap ... • Replace Implicit Tree with Composite (Refactoring to Patterns) • Refactoring to Composite loosens coupling to implicit tree • Builder loosens coupling to Composite
  • 4. Builder (GoF) • The construction of a complex object is separated from its representation so that the same construction process can create different representations • Builder Defines the required operations for creating various parts of a product • ConcreteBuilder Implements the operations declared in the Builder interface. • Director Builds a specific product via the interface exposed by the Builder object. • Product The concrete type the Builder object creates.
  • 5. Class Diagram 1_1196587101774 TagNode activityTag = new TagNode(“activity”); ... TagNode flavorsTag = new TagNode(“flavors”); activityTag.add(favorsTag); ... TagNode flavorTag = new TagNode(“flavor”); flavorsTag.add(flavorTag); Class Diagram 3_1196677789548 TagBuilder builder = new TagBuilder(“activity”); ... builder.addChild(“flavors”); ... builder.addToParent(“flavors”, “flavor”); ...
  • 6. Class Diagram 2_1196596929958 Document doc = new DocumentImpl(); Element orderTag = doc.createElement(“order”); orderTag.setAttribute(“id”, order.getOrderId()); Element productTag = doc.createElement(“product”); productTag.setAttribute(“id”, product.getID()); Text productName = doc.createTextNode(product.getName()); productTag.appendChild(productName); orderTag.appendChld(productTag); Class Diagram 4_1196679481681 DOMBuilder orderBuilder = new DOMBuilder(“order”) orderBuilder.addAttribute(“id”, order.getOrder()); orderBuilder.addChild(“product”); orderBuilder.addAttribute(“id”, product.getID()); orderBuilder.adValue(product.getName());
  • 7. Benefits Simplifies a client’s code for constructing a Composite Reduces the repetitive and error-prone nature of Composite creation Creates a loose coupling between client and Composite Allows for different representations of the encapsulated Composite or complex object • Liabilities May not have the most intention-revealing interface
  • 8. Mechanics 1. Create Builder 2. Make Builder capable of creating children 3. Make Builder capable of setting attributes on nodes 4. Reflect on interface ... simplify 5. Refactor Composite construction code to use Builder
  • 9. TagNode Revisited Class Diagram 5_1196681761272 * Composite interface ~ Builder interface
  • 10. Step 1. Create Builder public class TagBuilderTest ... public void testBuilderOneNode() { String expectedXml = “<flavors/>”; String actualXml = TagBuilder(“flavors”).toXml(); assertXmlEquals(expectedXml, actualXml); }
  • 11. Step 1. Create Builder public class TagBuilder { private TagNode rootNode; public TagBuilder(String rootTagName) { rootNode = new TagNode(rootTagName); } public String toXml() { return rootNode.toString(); } }
  • 12. Step 2. Support child creation and placement public class TagBuilderTest ... public void testBuilderOneChild() { String expectedXml = “<flavors>” + “<flavor/>” + “</flavors>”; TagBuilder builder = TagBuilder(“flavors”); builder.addChild(“flavor”); String actualXml = builder.toXml(); assertXmlEquals(expectedXml, actualXml); }
  • 13. Step 2. Support child creation and placement public class TagBuilder { private TagNode rootNode; private TagNode currentNode; public TagBuilder(String rootTagName) { rootNode = new TagNode(rootTagName); currentNode = rootNode; } pubic void addChild(String childTagName) { TagNode parentNode = currentNode; currentNode = new TagNode(childTagName); parentNode.addChild(curentNode); } ...
  • 14. Step 2. Support child creation and placement public class TagBuilderTest ... public void testBuilderOneChild() { String expectedXml = “<flavors>” + “<flavor1/>” + “<flavor2/>” + “</flavors>”; TagBuilder builder = TagBuilder(“flavors”); builder.addChild(“flavor1”); builder.addSibling(“flavor2”); String actualXml = builder.toXml(); assertXmlEquals(expectedXml, actualXml); }
  • 15. Step 2. Support child creation and placement public class TagBuilder ... pubic void addChild(String childTagName) { addTo(currentNode, childTagName); } public void addSibling(String siblingTagName) { addTo(currentNode.getParent(), siblingTagName); } private void addTo(TagNode parentNode, String tagName) { currentNode = new TagNode(tagName); parentNode.addChild(curentNode); } ... 1. Refactor Composite to support Builder 2. Thirdparty Composite?
  • 16. Step 3. Support attributes and values public class TagBuilderTest ... public void testAttributesAndVaues() { String expectedXml = “<flavor name=ʼTest-Driven Developmentʼ>” + “<requirements>” + “<requirement type=ʼhardwareʼ>” + “1 computer for every 2 participants” + “</requirement>” “</requirements>” + “</flavor>”; TagBuilder builder = TagBuilder(“flavor”); builder.addAttribute(“name”, “Test-Driven Development”); builder.addChild(“requirements”); builder.addToParent(“requirements”, “requirement”); builder.addAttribute(“type”, “hardware”); builder.addValue(“1 computer for every 2 participants”); String actualXml = builder.toXml(); assertXmlEquals(expectedXml, actualXml); }
  • 17. Step 3. Support attributes and values public class TagBuilder ... pubic void addAttribute(String name, String value) { currentNode.addAttribute(name, value); } public void addValue(String value) { currentNode.addValue(value); } ...
  • 18. Step 4. Reflect ... public class TagBuilder { public TagBuilder(String rootTagName) { ... } public void addChild(String childTagName) { ... } public void addSibling(String siblingTagName) { ... } public void addToParent(String parentTagName, String childTagName) { ... } public void addAttribute(String name, String value) { ... } public void addValue(String value) { ... } public String toXml() { ... } }
  • 19. public class TagBuilder { public TagBuilder(String rootTagName) { ... } public void addChild(String childTagName) { ... } public void addSibling(String siblingTagName) { ... } public void addToParent(String parentTagName, String childTagName) { ... } public void addAttribute(String name, String value); public void addValue(String value); public String toXml() { ... } } public class TagNode { public TagNode(String tagName) { ... } public void add(TagNode childNode) { ... } public void addAttribute(String name, String value) { ... } public void addValue(String value) { ... } public String toString() { ... } }
  • 20. Step 5. Replace Composite construction code public class CatalogWriter ... TagNode requirementsTag = new TagNode(“requirements”); flavorTag.add(requirementsTag); for (int i = 0; i < requirementsCount; ++i) { Requirement requirement = flavor.getRequirements()[i]; TagNode requirementTag = new TagNode(“requirement”); ... requirementsTag.add(requirementsTag); } public class CatalogWriter ... builder.addChild(“requirements”); for (int i = 0; i < requirementsCount; ++i) { Requirement requirement = flavor.getRequirements()[i]; builder.addToParent(“requirements”, “requirement”); ... }