SlideShare a Scribd company logo
1 of 23
Download to read offline
Uncommon Design Patterns

        STEFANO FAGO - 2003
Uncommon Design Patterns

G.O.F. Design Patterns are design tools
wide adopted by developers and architects working
with Object Oriented Technology and, on them, you
may experience a wide literature.
These Slides try to introduce some Design Pattern
less visible but very practical!
Uncommon Design Patterns

The Patterns are:

    Null Object
●


    Encapsulated Context
●


    Role Object
●


    ISP & Object Adaptation
●


    Essence
●
Null Object

It proposes the adoption of an object, in relation to a
given Type, to expresses the concept of NO
ACTION or EMPTY ELEMENT, respecting the
contract (the Interface) of the Type of which is a
surrogate. The issue that you want to solve is to
avoid the use of NULL/NIL in situations where
it is necessary to return a reference to an Object,
although there will be no processing.
Null Object

Supposing some code:
           InfoList availableUnits = manager.getOperativeUnitFor(...);
   for (Iterator iterator = availableUnits.iterator(); iterator.hasNext();) {
                // do something with unit
           }

to be able to processe without error we have to use a
nullity check:
       if(availableUnits != null){
           for (Iterator iterator = availableUnits.iterator(); iterator.hasNext();) {
               // do something with unit
           }
       }
Null Object

We can avoid this issue with Null Object
     InfoList getOperativeUnitFor(String nationCode, String areaCode) {
         InfoList result =
         // ...seach for...
         // if there no Unit and Empty List is returned...
         result = new VoidInfoList();
         return result;
     }

so the code can became:
     InfoList availableUnits = manager.getOperativeUnitFor(...);
         for (Iterator iterator = availableUnits.iterator(); iterator.hasNext();) {
             // do something with unit
         }
Encapsulated Context

In complex systems, it becomes necessary to use
common data, with global visibility, such as
configuration data. The use of global elements is a
practice not recommended in Object Oriented
Systems, and even if the GOF Singleton Pattern can
offer a way out, its abuse can be detrimental.
Encapsulated Context

Supposing to have different Component that need to
share common services such as Logging, Order
Management and recieve also specific messages.
Every Component must have a method with
signature:

  process(SomeMsg msg, OrdersManager ordMan, Logger log){
    ...
  }
Encapsulated Context

If the number of Common Services grow, we can
have a signature mess!
So we need a single object to encapsulate the
different services without using global object but
using injection on method...
        process(ProcessContext ctx){
          Msg msg = ctx.getActualMsg(); ctx.log(...);
          ctx.processLastOrder(); ...
        }
Role Object

On large size design is easy to deal with a modeling
problem: an element can plays different roles
depending on the context in which it is placed.

The idea of Role can be developed from the concept
of interface and use multiple inheritance to compose
different roles: this approach can lead to an
object unwieldy and difficult to manage!
Role Object

Objective of the Role Object Pattern is to offer a
solution to the problem of roles thanks to a set of
Role Objects that are dynamically added or removed
compared to a Core Object.
Role Object

We can use the simple example of Employee and
different roles that this element can plays!
interface Employee:
      interface Employee{
                String getName();
                long getId();
                boolean hasRole(String role);
                EmployeeRole getRole(String role);
                void removeRole(String role);
                void addRole(String role);
            }
Role Object

Now we can define the Core Object and Role
Objects:
     class EmployeeCore implements Employee{
       private Map roles = ...
      public boolean hasRole(String role) { return roles.containsKey(role);}
      public EmployeeRole getRole(String role) {return (EmployeeRole)
       roles.get(role);}
     public void addRole(String role, EmployeeRole impl) {roles.put(role,
       impl);}
      public void removeRole(String role) {roles.remove(role); }
     ... }
Role Object

    class EmployeeRole implements Employee{

     private EmployeeCore core; ...
     String getName(){ return core.getName(); } ...
     boolean hasRole(String role) { return core.hasRole(); }
    ... }


    class Director extends EmployeeRole{ Director(EmployeeCore core)...}

    class Buyer extends EmployeeRole{ Buyer(EmployeeCore core)...}
Role Object

We can construct the complex object:
            EmployeeCore [] empls = new EmployeeCore[3];
            empls[0] = new EmployeeCore();
            empls[1] = new EmployeeCore();
            empls[2] = new EmployeeCore();
            Director d = new Director(empls[0]);
            empls[0].addRole(quot;directorquot;,d);
            Buyer b = new Buyer(empls[2]);
            empls[2].addRole(quot;buyerquot;,b);


We can hide complex object with a manager:
        Employee emp = manager.getEmployee(...);
Role Object

Follow, the sample usage:
          Employee emp = manager.getEmployee(...);

          if (emp.hasRole(quot;directorquot;)) {
            Director director = (Director)emp;
            ...
          }

          if (emp.hasRole(quot;buyerquot;)) {
            Buyer buyer = (Buyer)emp;
            ...
          }
ISP & Object Adaptation

Inspired by PEP 246 (Python Language)
any object might quot;embodyquot; a protocol:

         adapt(component, protocol[, default])

    checks if component directly implements protocol
●



    checks if protocol knows how to adapt component
●



    else falls back to a registry of adapters indexed by
●

    type(component) [[or otherwise, e.g. by URI]]
    last ditch: returns default or raises an exception
●
ISP & Object Adaptation

    We first define ad adaptable protocol then define
●

    the adapters and register them; at last we use type
    to play ;-)


    Our simple protocol:
●


             public interface Adaptable
             {
               public Object adapt(Class targetType);
             }
ISP & Object Adaptation

    Define some target Contracts and Adapters:
●


     public interface Reader { public Object read();   }
     public interface Shape { public float area(); public void draw(); }

     public interface Writer { public void write(Object o); }

     public class ShapeReaderAdapter{ ... }
     public class ShapeWriterAdapter{...}

    Register Contracts with relative Adapters:
●


     AdapterRegistry.registerAdapter( Shape.class, Reader.class,
      ShapeReaderAdapter.class);
    AdapterRegistry.registerAdapter( Shape.class, Writer.class,
      ShapeWriterAdapter.class);
ISP & Object Adaptation

    Define some Adaptable:
●


        public class Circle implements Shape, Adaptable{
               public float area() {... } public void draw() {...}
               public Object adapt(Class targetType) {
                  return AdapterRegistry.getAdapter(this,targetType);
              }
         }



    Use Object Adaptation:
●


        Circle circle = new Circle();
       Writer writer = (Writer) circle.adapt(Writer.class);
Essence Pattern

This Design use a particular class identified as
Essence that encapsulates the basic properties for
the configuration and validation of the target Object.
Once the object Essence is instantiated, the
validation of the elements is fired and only if this
operation has successfully, it's created the object of
target Type, set with the same Essence properties.
Essence Pattern
Essence Pattern

    public class Server {
        public Server(ServerEssence essence) { ... }
        ... }


    public class ServerEssence {
        public void setHost(String host) { ... } public String getHost() { ... }
        public void setPort(int port) { ... } public int getPort() { ... }
        // other methods
        public Server getServer() {
           if (isValid()) return new Server(this);
                throw new InvalidServerConfigurationException(this);
        } ...
    }

More Related Content

What's hot

React vs Angular
React vs Angular React vs Angular
React vs Angular Appinventiv
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questionsgirichinna27
 
Introduction to three.js
Introduction to three.jsIntroduction to three.js
Introduction to three.jsyuxiang21
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
Selenium interview-questions-freshers
Selenium interview-questions-freshersSelenium interview-questions-freshers
Selenium interview-questions-freshersNaga Mani
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkHumberto Marchezi
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test frameworkAbner Chih Yi Huang
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
Node.js, Uma breve introdução
Node.js, Uma breve introduçãoNode.js, Uma breve introdução
Node.js, Uma breve introduçãoPablo Feijó
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual StudioMuhammad Aqeel
 
Angular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web ApplicationsAngular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web ApplicationsAlbiorix Technology
 
Aprendendo Angular com a CLI
Aprendendo Angular com a CLIAprendendo Angular com a CLI
Aprendendo Angular com a CLIVanessa Me Tonini
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Google Chrome DevTools features overview
Google Chrome DevTools features overviewGoogle Chrome DevTools features overview
Google Chrome DevTools features overviewOleksii Prohonnyi
 
Angular Best Practices - Perfomatix
Angular Best Practices - PerfomatixAngular Best Practices - Perfomatix
Angular Best Practices - PerfomatixPerfomatix Solutions
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel ProgrammingRamazan AYYILDIZ
 
Python Testing 101 with Selenium
Python Testing 101 with SeleniumPython Testing 101 with Selenium
Python Testing 101 with SeleniumLeonardo Jimenez
 

What's hot (20)

Angular vs. React
Angular vs. ReactAngular vs. React
Angular vs. React
 
React vs Angular
React vs Angular React vs Angular
React vs Angular
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
 
Introduction to three.js
Introduction to three.jsIntroduction to three.js
Introduction to three.js
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Selenium interview-questions-freshers
Selenium interview-questions-freshersSelenium interview-questions-freshers
Selenium interview-questions-freshers
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing Framework
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
Google test training
Google test trainingGoogle test training
Google test training
 
Node.js, Uma breve introdução
Node.js, Uma breve introduçãoNode.js, Uma breve introdução
Node.js, Uma breve introdução
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual Studio
 
Three.js basics
Three.js basicsThree.js basics
Three.js basics
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Angular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web ApplicationsAngular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web Applications
 
Aprendendo Angular com a CLI
Aprendendo Angular com a CLIAprendendo Angular com a CLI
Aprendendo Angular com a CLI
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Google Chrome DevTools features overview
Google Chrome DevTools features overviewGoogle Chrome DevTools features overview
Google Chrome DevTools features overview
 
Angular Best Practices - Perfomatix
Angular Best Practices - PerfomatixAngular Best Practices - Perfomatix
Angular Best Practices - Perfomatix
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Python Testing 101 with Selenium
Python Testing 101 with SeleniumPython Testing 101 with Selenium
Python Testing 101 with Selenium
 

Similar to Uncommon Design Patterns

DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptAntoJoseph36
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
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
 
C questions
C questionsC questions
C questionsparm112
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsZohar Arad
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 

Similar to Uncommon Design Patterns (20)

DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
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
 
C questions
C questionsC questions
C questions
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Day 1
Day 1Day 1
Day 1
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 

More from Stefano Fago

Exploring Open Source Licensing
Exploring Open Source LicensingExploring Open Source Licensing
Exploring Open Source LicensingStefano Fago
 
Non solo Microservizi: API, Prodotti e Piattaforme
Non solo Microservizi: API, Prodotti e PiattaformeNon solo Microservizi: API, Prodotti e Piattaforme
Non solo Microservizi: API, Prodotti e PiattaformeStefano Fago
 
Don’t give up, You can... Cache!
Don’t give up, You can... Cache!Don’t give up, You can... Cache!
Don’t give up, You can... Cache!Stefano Fago
 
Resisting to The Shocks
Resisting to The ShocksResisting to The Shocks
Resisting to The ShocksStefano Fago
 
Gamification - Introduzione e Idee di un NON GIOCATORE
Gamification - Introduzione e Idee di un NON GIOCATOREGamification - Introduzione e Idee di un NON GIOCATORE
Gamification - Introduzione e Idee di un NON GIOCATOREStefano Fago
 
Quale IT nel futuro delle Banche?
Quale IT nel futuro delle Banche?Quale IT nel futuro delle Banche?
Quale IT nel futuro delle Banche?Stefano Fago
 
Microservices & Bento
Microservices & BentoMicroservices & Bento
Microservices & BentoStefano Fago
 
What drives Innovation? Innovations And Technological Solutions for the Distr...
What drives Innovation? Innovations And Technological Solutions for the Distr...What drives Innovation? Innovations And Technological Solutions for the Distr...
What drives Innovation? Innovations And Technological Solutions for the Distr...Stefano Fago
 
Reasoning about QRCode
Reasoning about QRCodeReasoning about QRCode
Reasoning about QRCodeStefano Fago
 
... thinking about Microformats!
... thinking about Microformats!... thinking about Microformats!
... thinking about Microformats!Stefano Fago
 
Riuso Object Oriented
Riuso Object OrientedRiuso Object Oriented
Riuso Object OrientedStefano Fago
 

More from Stefano Fago (13)

Exploring Open Source Licensing
Exploring Open Source LicensingExploring Open Source Licensing
Exploring Open Source Licensing
 
Non solo Microservizi: API, Prodotti e Piattaforme
Non solo Microservizi: API, Prodotti e PiattaformeNon solo Microservizi: API, Prodotti e Piattaforme
Non solo Microservizi: API, Prodotti e Piattaforme
 
Api and Fluency
Api and FluencyApi and Fluency
Api and Fluency
 
Don’t give up, You can... Cache!
Don’t give up, You can... Cache!Don’t give up, You can... Cache!
Don’t give up, You can... Cache!
 
Resisting to The Shocks
Resisting to The ShocksResisting to The Shocks
Resisting to The Shocks
 
Gamification - Introduzione e Idee di un NON GIOCATORE
Gamification - Introduzione e Idee di un NON GIOCATOREGamification - Introduzione e Idee di un NON GIOCATORE
Gamification - Introduzione e Idee di un NON GIOCATORE
 
Quale IT nel futuro delle Banche?
Quale IT nel futuro delle Banche?Quale IT nel futuro delle Banche?
Quale IT nel futuro delle Banche?
 
Microservices & Bento
Microservices & BentoMicroservices & Bento
Microservices & Bento
 
Giochi in Azienda
Giochi in AziendaGiochi in Azienda
Giochi in Azienda
 
What drives Innovation? Innovations And Technological Solutions for the Distr...
What drives Innovation? Innovations And Technological Solutions for the Distr...What drives Innovation? Innovations And Technological Solutions for the Distr...
What drives Innovation? Innovations And Technological Solutions for the Distr...
 
Reasoning about QRCode
Reasoning about QRCodeReasoning about QRCode
Reasoning about QRCode
 
... thinking about Microformats!
... thinking about Microformats!... thinking about Microformats!
... thinking about Microformats!
 
Riuso Object Oriented
Riuso Object OrientedRiuso Object Oriented
Riuso Object Oriented
 

Recently uploaded

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
 
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
 
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
 
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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
[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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Recently uploaded (20)

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 ...
 
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...
 
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
 
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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
[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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

Uncommon Design Patterns

  • 1. Uncommon Design Patterns STEFANO FAGO - 2003
  • 2. Uncommon Design Patterns G.O.F. Design Patterns are design tools wide adopted by developers and architects working with Object Oriented Technology and, on them, you may experience a wide literature. These Slides try to introduce some Design Pattern less visible but very practical!
  • 3. Uncommon Design Patterns The Patterns are: Null Object ● Encapsulated Context ● Role Object ● ISP & Object Adaptation ● Essence ●
  • 4. Null Object It proposes the adoption of an object, in relation to a given Type, to expresses the concept of NO ACTION or EMPTY ELEMENT, respecting the contract (the Interface) of the Type of which is a surrogate. The issue that you want to solve is to avoid the use of NULL/NIL in situations where it is necessary to return a reference to an Object, although there will be no processing.
  • 5. Null Object Supposing some code: InfoList availableUnits = manager.getOperativeUnitFor(...); for (Iterator iterator = availableUnits.iterator(); iterator.hasNext();) { // do something with unit } to be able to processe without error we have to use a nullity check: if(availableUnits != null){ for (Iterator iterator = availableUnits.iterator(); iterator.hasNext();) { // do something with unit } }
  • 6. Null Object We can avoid this issue with Null Object InfoList getOperativeUnitFor(String nationCode, String areaCode) { InfoList result = // ...seach for... // if there no Unit and Empty List is returned... result = new VoidInfoList(); return result; } so the code can became: InfoList availableUnits = manager.getOperativeUnitFor(...); for (Iterator iterator = availableUnits.iterator(); iterator.hasNext();) { // do something with unit }
  • 7. Encapsulated Context In complex systems, it becomes necessary to use common data, with global visibility, such as configuration data. The use of global elements is a practice not recommended in Object Oriented Systems, and even if the GOF Singleton Pattern can offer a way out, its abuse can be detrimental.
  • 8. Encapsulated Context Supposing to have different Component that need to share common services such as Logging, Order Management and recieve also specific messages. Every Component must have a method with signature: process(SomeMsg msg, OrdersManager ordMan, Logger log){ ... }
  • 9. Encapsulated Context If the number of Common Services grow, we can have a signature mess! So we need a single object to encapsulate the different services without using global object but using injection on method... process(ProcessContext ctx){ Msg msg = ctx.getActualMsg(); ctx.log(...); ctx.processLastOrder(); ... }
  • 10. Role Object On large size design is easy to deal with a modeling problem: an element can plays different roles depending on the context in which it is placed. The idea of Role can be developed from the concept of interface and use multiple inheritance to compose different roles: this approach can lead to an object unwieldy and difficult to manage!
  • 11. Role Object Objective of the Role Object Pattern is to offer a solution to the problem of roles thanks to a set of Role Objects that are dynamically added or removed compared to a Core Object.
  • 12. Role Object We can use the simple example of Employee and different roles that this element can plays! interface Employee: interface Employee{ String getName(); long getId(); boolean hasRole(String role); EmployeeRole getRole(String role); void removeRole(String role); void addRole(String role); }
  • 13. Role Object Now we can define the Core Object and Role Objects: class EmployeeCore implements Employee{ private Map roles = ... public boolean hasRole(String role) { return roles.containsKey(role);} public EmployeeRole getRole(String role) {return (EmployeeRole) roles.get(role);} public void addRole(String role, EmployeeRole impl) {roles.put(role, impl);} public void removeRole(String role) {roles.remove(role); } ... }
  • 14. Role Object class EmployeeRole implements Employee{ private EmployeeCore core; ... String getName(){ return core.getName(); } ... boolean hasRole(String role) { return core.hasRole(); } ... } class Director extends EmployeeRole{ Director(EmployeeCore core)...} class Buyer extends EmployeeRole{ Buyer(EmployeeCore core)...}
  • 15. Role Object We can construct the complex object: EmployeeCore [] empls = new EmployeeCore[3]; empls[0] = new EmployeeCore(); empls[1] = new EmployeeCore(); empls[2] = new EmployeeCore(); Director d = new Director(empls[0]); empls[0].addRole(quot;directorquot;,d); Buyer b = new Buyer(empls[2]); empls[2].addRole(quot;buyerquot;,b); We can hide complex object with a manager: Employee emp = manager.getEmployee(...);
  • 16. Role Object Follow, the sample usage: Employee emp = manager.getEmployee(...); if (emp.hasRole(quot;directorquot;)) { Director director = (Director)emp; ... } if (emp.hasRole(quot;buyerquot;)) { Buyer buyer = (Buyer)emp; ... }
  • 17. ISP & Object Adaptation Inspired by PEP 246 (Python Language) any object might quot;embodyquot; a protocol: adapt(component, protocol[, default]) checks if component directly implements protocol ● checks if protocol knows how to adapt component ● else falls back to a registry of adapters indexed by ● type(component) [[or otherwise, e.g. by URI]] last ditch: returns default or raises an exception ●
  • 18. ISP & Object Adaptation We first define ad adaptable protocol then define ● the adapters and register them; at last we use type to play ;-) Our simple protocol: ● public interface Adaptable { public Object adapt(Class targetType); }
  • 19. ISP & Object Adaptation Define some target Contracts and Adapters: ● public interface Reader { public Object read(); } public interface Shape { public float area(); public void draw(); } public interface Writer { public void write(Object o); } public class ShapeReaderAdapter{ ... } public class ShapeWriterAdapter{...} Register Contracts with relative Adapters: ● AdapterRegistry.registerAdapter( Shape.class, Reader.class, ShapeReaderAdapter.class); AdapterRegistry.registerAdapter( Shape.class, Writer.class, ShapeWriterAdapter.class);
  • 20. ISP & Object Adaptation Define some Adaptable: ● public class Circle implements Shape, Adaptable{ public float area() {... } public void draw() {...} public Object adapt(Class targetType) { return AdapterRegistry.getAdapter(this,targetType); } } Use Object Adaptation: ● Circle circle = new Circle(); Writer writer = (Writer) circle.adapt(Writer.class);
  • 21. Essence Pattern This Design use a particular class identified as Essence that encapsulates the basic properties for the configuration and validation of the target Object. Once the object Essence is instantiated, the validation of the elements is fired and only if this operation has successfully, it's created the object of target Type, set with the same Essence properties.
  • 23. Essence Pattern public class Server { public Server(ServerEssence essence) { ... } ... } public class ServerEssence { public void setHost(String host) { ... } public String getHost() { ... } public void setPort(int port) { ... } public int getPort() { ... } // other methods public Server getServer() { if (isValid()) return new Server(this); throw new InvalidServerConfigurationException(this); } ... }