SlideShare a Scribd company logo
Java course - IAG0040




             Design Patterns




Anton Keks                           2011
The Increasing Complexity

     Complexity of software systems
                                          Time

     New programming paradigms
     Higher level of abstraction
     HW Assembler    Structural P. (DSL, AOP?)
       CPUs  Procedural P.      OOP            ...

Java course – IAG0040                          Lecture 11
Anton Keks                                         Slide 2
The emerge of OOP
 ●
     Response to complexity
 ●   Software crisis: difficulty of writing correct,
     understandable, and verifiable programs

 ●
     Emphasizes modularity & reusability
 ●
     Solves the “Tramp Data” problem
 ●
     Closer to the Real World
 ●
     Program == cooperating objects,
     not a list of instructions
Java course – IAG0040                           Lecture 11
Anton Keks                                          Slide 3
What are design patterns?
 ●
     Anywhere in the world you can find recurring
     patterns
 ●
     Design patterns
     –   are building blocks of a system's architecture
     –   are recurring solutions to design problems
         that you see over
     –   identify and specify abstractions that are
         above the level of single classes and instances


Java course – IAG0040                             Lecture 11
Anton Keks                                            Slide 4
Where do they come from?
 ●
     First referenced in early 80's,
     with the emerge of OOP
 ●   Formally defined in 1994 in the GOF book
     (even before Java!)
 ●
     Hundreds more have been identified since
     then

 ●
     Are usually discovered (through pattern-
     mining) rather than invented
Java course – IAG0040                           Lecture 11
Anton Keks                                          Slide 5
GOF (Gang of Four) book
                        ●
                            Title: Design Patterns:
                            Elements of Reusable
                            Object-Oriented
                            Software
                        ●
                            Is the first and essential
                            book on patterns
                        ●
                            Patterns are well
                            classified and described
                        ●   Every professional
                            software developer must
                            know them
Java course – IAG0040                           Lecture 11
Anton Keks                                          Slide 6
MVC
 ●
     Model-View-Controller
 ●
     One of the first patterns, comes from Smalltalk language
 ●
     Is a “best practice” of splitting GUI applications into
      –   Model - holds/stores data and provides data access interface
      –   View - displays data to the user obtained from the model
      –   Controller - manipulates the model, selects appropriate views
 ●   Therefore, the code consists of three decoupled layers, which
     can work together or independently
 ●   Any of the layers can be modified/rewritten without
     modifications to other layers

Java course – IAG0040                                          Lecture 11
Anton Keks                                                         Slide 7
Pattern classification
●   The GOF book defines 3 major types of patterns:
    –   Creational patterns are ones that create objects for
        you, rather than having you instantiate objects directly.
        This gives your program more flexibility in deciding
        which objects need to be created for a given case.
    –   Structural patterns help you compose groups of objects
        into larger structures, such as complex user interfaces
        or accounting data.
    –   Behavioral patterns help you define the
        communication between objects in your system and
        how the flow is controlled in a complex program.

Java course – IAG0040                                    Lecture 11
Anton Keks                                                   Slide 8
Anti-patterns
 ●
     This term is also widely used to define certain
     patterns, which should be avoided in software design
 ●
     Anti-patterns (aka pitfalls) are commonly reinvented
     bad solutions to problems
 ●
     Knowing anti-patterns is as important as knowing
     patterns
 ●   Another term used in Agile Software Development is
     code smell (eliminated by refactoring)
 ●
     See Wikipedia articles on both Anti-pattern and
     Code smell for more info and examples
Java course – IAG0040                              Lecture 11
Anton Keks                                             Slide 9
Software Design vs Architecture
 ●
     Software design is the structure of code and
     relations between its elements (classes)
 ●   Software architecture is the same as software
     design, but used when people want to make it
     look important (after Martin Fowler)
     –   Architecture is the part of design that is
         difficult to change
     –   Therefore it is undesired :-)


Java course – IAG0040                             Lecture 11
Anton Keks                                          Slide 10
Some design considerations
 ●
     Thinking about design is very important at all
     stages during a project. If it needs corrections
     then refactoring should be used
 ●
     Consistent API and loosely coupled code are
     very important - they make changes easy
 ●
     Unit tests and TDD help a lot
 ●
     Design patterns help make your design better
     and more understandable to others


Java course – IAG0040                           Lecture 11
Anton Keks                                        Slide 11
General concepts of design
 ●
     Fundamental reason for patterns: keep classes
     separated, prevent them from knowing too much
     about each other
 ●
     Abstract classes and interfaces are major tools
 ●
     Program to interfaces, not to implementations
 ●   Prefer object composition to inheritance; it usually
     results in cleaner code (this is simply a construction
     of objects that contain others)
     –   Delegation may be used for reusing “parent” behavior


Java course – IAG0040                                  Lecture 11
Anton Keks                                               Slide 12
Iterator
 ●
     Behavioral pattern, synonym: Cursor
 ●
     You already know it from the Collections API!
 ●
     Iterator provides a way for accessing elements of an
     aggregate object sequentially without exposing its
     underlying representation
 ●
     Iterator is a special object provided by an aggregate
     object for holding of iteration state
     –   better than if aggregate objects change their state during
         iteration (e.g. provide their own next() methods)
     –   better than index-based element access - hides
         implementation details
     –   several iterators may be used at once on the same data
Java course – IAG0040                                          Lecture 11
Anton Keks                                                       Slide 13
Lazy Initialization
 ●
     The idea is to initialize “expensive” objects on demand, e.g.
     only when they are accessed (this is sometimes referred to as
     “caching”)
      –   if expensive object is never accessed then it is never created
 ●   If initialization takes time and several threads access the object,
     then synchronization is needed
 ●   Double-checked locking is a clever (but broken) trick:
      –   public Object getExpensiveObject() {
             if (instance == null) {
                 synchronized (this) {
                    if (instance == null)
                        instance = new ...
                 }
             }
             return instance;
          }
Java course – IAG0040                                                Lecture 11
Anton Keks                                                             Slide 14
Singleton
 ●
     Creational pattern, sometimes uses lazy initialization
 ●
     Ensures a class has only one instance, and provides
     global access point to it
 ●   public class Singleton {
        private Singleton() {} // private constructor
        private static Singleton uniqueInstance =
                                  new Singleton();
        public static Singleton getInstance() {
           return uniqueInstance;
           // can be lazily initialized
        }
     }



Java course – IAG0040                                Lecture 11
Anton Keks                                             Slide 15
Singleton (2)
 ●   Better than global variables (controlled access,
     doesn't pollute namespace)
 ●   More flexible than class operations (static
     methods): can be polymorphic and subclassed,
     permits easy design changes, etc
 ●   Disadvantages: may result in coupled code, if
     used directly too much. Difficult to mock in unit
     tests
 ●   (better alternative – use singletons in an IoC
     container, like PicoContainer or Spring)
Java course – IAG0040                            Lecture 11
Anton Keks                                         Slide 16
Factory Method
 ●   Creational pattern, synonyms: Factory, Virtual
     Constructor
 ●   Defines an interface for creating an object of
     particular abstract type, but lets subclasses decide
     which concrete class to instantiate
 ●   Used by many modern frameworks and APIs (e.g.
     SAXParserFactory)
 ●   public class BulldogFactory implements DogFactory {
        public Dog createDog() { return new Bulldog(); } }
 ●   public class DachshundFactory implements DogFactory {
        public Dog createDog() {
           return new Dachshund(); } }
Java course – IAG0040                                 Lecture 11
Anton Keks                                              Slide 17
Factory Method (2)
 ●
     Allows writing of polymorphic code that can work
     with different implementations of interfaces without
     any direct references to them, eliminates hardcoding
     of implementation class names
 ●   The method must be non-static, if you want to override
     it in a superclass of factory
 ●   Variation: factory method can be static and decide
     itself what to instantiate
     –   using configuration
     –   with the help of parameters

Java course – IAG0040                                Lecture 11
Anton Keks                                             Slide 18
Abstract Factory
 ●
     Creational pattern, synonym: Kit
 ●
     Provides an interface for creating families of related
     or dependent objects without specifying their
     concrete classes
 ●
     Abstract Factory is similar to Factory Method with the
     exception that methods are never static and
     Factories are always subclassed in order to return
     different sets of instances




Java course – IAG0040                                Lecture 11
Anton Keks                                             Slide 19
Abstract Factory (2)
 ●
     Example: GUI toolkit with Factories for creation of
     widgets with different look and feel
 ●   public interface AbstractWidgetFactory {
        public Button createButton();
        public ScrollBar createScrollBar();
     }

     public class MotifLookAndFeelWidgetFactory
        implements AbstractWidgetFactory {
        ...
     }




Java course – IAG0040                               Lecture 11
Anton Keks                                            Slide 20
Builder
 ●
     Creational pattern
 ●
     Eliminates 'telescoping' constructors
     –   without sacrificing immutability
     –   has all advantages of Factory
 ●
     Create Builder inner static class with methods returning
     'this' and build() method returning the class instance
 ●   Pizza pizza = new Pizza.Builder().
       withOnion().doubleCheese().build();
 ●
     Very readable, better than infinite number of constructors
     with boolean or numeric arguments, or setters

Java course – IAG0040                                   Lecture 11
Anton Keks                                                Slide 21
Common structural patterns

 ● Decorator
 ● Adapter


 ●
   Composite
 ● (Proxy)




Java course – IAG0040            Lecture 11
Anton Keks                         Slide 22
Decorator
 ●   Structural pattern, synonym: Wrapper
 ●   Attach additional responsibilities to an object
     dynamically.
 ●   Decorators provide a flexible alternative to
     subclassing for extending functionality
 ●   Useful for adding responsibilities dynamically to
     objects, not classes.
 ●
     Decorator must have the same interface as the
     decorated object.

Java course – IAG0040                               Lecture 11
Anton Keks                                            Slide 23
Decorator (2)
 ●
     Decorator delegates all method calls to wrapped
     instance and does something else before or after.
     Every object can be decorated several times.
 ●   BufferedInputStream decorates any
     InputStream
 ●   public class LoggingConnection implements Connection {
        private Connection conn;
        ...
        public boolean isActive() {
            System.out.println(“isActive was called!”);
            return conn.isActive();
        }
        ...
     }

Java course – IAG0040                                 Lecture 11
Anton Keks                                              Slide 24
Adapter
 ●
     Structural pattern, synonym: Wrapper
 ●   Converts the interface of a class into another
     interface clients expect
 ●
     Adapter lets classes work together that
     couldn't otherwise because of incompatible
     interfaces




Java course – IAG0040                          Lecture 11
Anton Keks                                       Slide 25
Adapter (2)
 ●
     In other words, Adapter just translates requests to
     another API of the wrapped class
 ●
     Examples
     –   InputStreamReader adapts an InputStream to
         the Reader interface
     –   Arrays.asList() represents java arrays as List
         instances
     –   Collections.enumeration() represents
         Iterators as Enumerations


Java course – IAG0040                                Lecture 11
Anton Keks                                             Slide 26
Composite
 ●
     Structural pattern, similar to Decorator
 ●   Composes objects into tree structures to
     represent part-whole hierarchies
 ●
     Composite lets clients treat individual objects
     and compositions of objects uniformly




Java course – IAG0040                           Lecture 11
Anton Keks                                        Slide 27
Composite (2)
 ●   Example: in a GUI toolkit, a Window is a
     composite of other Widgets, while is a Widget
     itself
 ●   Many GUI toolkits have base classes named
     Composite, which can have a layout manager
     assigned and an arbitrary number of child
     Composites
 ●   SequenceInputStream is a composite of many
     InputStreams


Java course – IAG0040                           Lecture 11
Anton Keks                                        Slide 28
Proxy
 ●
     Decorator, Adapter, and Composite
     –   any of them can be called 'Proxy'
 ●
     Proxy is a class, functioning as an interface to
     another thing
 ●
     In a more specific sense (Virtual Proxy):
     wrapping classes can
     –   control access to wrapped objects
     –   lazily initialize the delegates inside them


Java course – IAG0040                                  Lecture 11
Anton Keks                                               Slide 29
Strategy
●
    Behavioral pattern, synonym: Policy
●
    Defines a family of algorithms, encapsulates each one,
    and makes them interchangeable; eliminates
    conditions from the code (GoF)
●
    Capture the abstraction in an interface, bury
    implementation details in derived classes
●   Strategy lets the algorithm vary independently from
    clients that use it
    –   Algorithms can be changed on-the-fly at runtime


Java course – IAG0040                               Lecture 11
Anton Keks                                            Slide 30
Strategy (2)
 ●
     Strategy pattern allows adding of new algorithms
     easily and/or dynamically
 ●
     Participants:
     –   Strategy – an interface or abstract class of all
         strategies
     –   ConcreteStrategy – each is a different
         implementation of Strategy
     –   Context – a class, initialized to use and maintain a
         ConcreteStrategy, can provide additional (context
         specific) data to it

Java course – IAG0040                                   Lecture 11
Anton Keks                                                Slide 31
State
 ●
     Behavioral pattern, similar to Strategy
 ●   Each “Strategy” is one of the states of the
     Context
     –   Strategy usually represents a single abstraction
     –   each State can implement several behaviors
         (different actions, methods)
     –   State interface may as well provide methods for
         transitions in order to implement a Finite State
         Machine

Java course – IAG0040                                 Lecture 11
Anton Keks                                              Slide 32
Façade
 ●   Structural pattern
 ●
     Provides a unified interface to a set of interfaces in subsystem
 ●   Facade defines a higher-level interface that makes the subsystem
     easier to use
 ●   Structuring a system into subsystems reduces complexity. Then
     subsystems can communicate only through Facades, while using
     their own lower-level interfaces internally. This reduces coupling
 ●   Example: consider internals of a compiler: it can have classes like
     Scanner, Parser, ProgramNode, BytecodeStream, etc, but externally
     you use the Facade class named Compiler, which simply takes input
     file and produces an output file
 ●
     Facade just delegates requests to appropriate subsystem classes, it
     doesn't do anything itself
Java course – IAG0040                                             Lecture 11
Anton Keks                                                          Slide 33
Prototype
 ●   Creational pattern
 ●
     Specifies the kind of objects to create using the
     prototypical instance
      –   creates new objects by copying (cloning) the prototype
 ●   Allows having an initialized reference instance of some
     abstract class, then it can be cloned or recreated with
     reflection API for creation of new objects
 ●   Useful when creating new instances is too complex (and
     slow) or less convenient than cloning
 ●   Convenient for implementation of plug-in architectures,
     where implementations may be added/removed dynamically

Java course – IAG0040                                      Lecture 11
Anton Keks                                                   Slide 34
Observer
 ●
     Behavioral pattern, synonym: Publish-
     Subscribe
 ●   Defines a one-to-many dependency between
     objects so that when one object changes
     state, all its dependents are notified and
     updated automatically
 ●
     Provides decoupled classes, which can work
     together or independently


Java course – IAG0040                        Lecture 11
Anton Keks                                     Slide 35
Observer (2)
 ●
     Participants:
     –   Subject (Observable) – the data to observe
     –   Observer – an updating interface for objects, which
         are notified
     –   ConcreteSubject – sends notifications to all
         registered ConcreteObservers
     –   ConcreteObserver – knows about ConcreteSubject,
         updates itself on notifications
 ●   Java provides both Observable abstract class and
     Observer interface
Java course – IAG0040                                   Lecture 11
Anton Keks                                                Slide 36

More Related Content

What's hot

Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
Sanae BEKKAR
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
Amit Kabra
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Abstract class
Abstract classAbstract class
Abstract class
Tony Nguyen
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
Shahriar Iqbal Chowdhury
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
Mudasir Qazi
 
Object Oriented Relationships
Object Oriented RelationshipsObject Oriented Relationships
Object Oriented Relationships
Taher Barodawala
 
Applets
AppletsApplets
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 

What's hot (20)

OOP java
OOP javaOOP java
OOP java
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Abstract class
Abstract classAbstract class
Abstract class
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
 
Object Oriented Relationships
Object Oriented RelationshipsObject Oriented Relationships
Object Oriented Relationships
 
Applets
AppletsApplets
Applets
 
Java threads
Java threadsJava threads
Java threads
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 

Viewers also liked

Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
Ender Aydin Orak
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
Chetan Gole
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
guy_davis
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The World
Saurabh Moody
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
Aniruddha Chakrabarti
 
PATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternPATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design Pattern
Michael Heron
 
Factory design pattern
Factory design patternFactory design pattern
Factory design patternFarhad Safarov
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
Mudasir Qazi
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1
Tom Chen
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter patternbabak danyal
 
Adapter design-pattern2015
Adapter design-pattern2015Adapter design-pattern2015
Adapter design-pattern2015
Vic Tarchenko
 
Anti patterns part 1
Anti patterns part 1Anti patterns part 1
Anti patterns part 1
Return on Intelligence
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)APU
 
Floor plan for cashew factory by sotonye anga
Floor plan for cashew factory by sotonye angaFloor plan for cashew factory by sotonye anga
Floor plan for cashew factory by sotonye anga
Sotonye anga
 
William Bronchick Coaching
William Bronchick CoachingWilliam Bronchick Coaching
William Bronchick Coaching
WilliamBronchick123
 
Performance management system slide
Performance management system slidePerformance management system slide
Performance management system slide
raizanamiza
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
Akshat Vig
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
Shakil Ahmed
 

Viewers also liked (20)

Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The World
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
PATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternPATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design Pattern
 
Factory design pattern
Factory design patternFactory design pattern
Factory design pattern
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter pattern
 
Adapter design-pattern2015
Adapter design-pattern2015Adapter design-pattern2015
Adapter design-pattern2015
 
Anti patterns part 1
Anti patterns part 1Anti patterns part 1
Anti patterns part 1
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)
 
Floor plan for cashew factory by sotonye anga
Floor plan for cashew factory by sotonye angaFloor plan for cashew factory by sotonye anga
Floor plan for cashew factory by sotonye anga
 
William Bronchick Coaching
William Bronchick CoachingWilliam Bronchick Coaching
William Bronchick Coaching
 
Performance management system slide
Performance management system slidePerformance management system slide
Performance management system slide
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 

Similar to Java Course 11: Design Patterns

Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
Anton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
Anton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
Anton Keks
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
Sujit Pathak
 
JavaFX in Action Part I
JavaFX in Action Part IJavaFX in Action Part I
JavaFX in Action Part I
Mohammad Hossein Rimaz
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
siragezeynu
 
Java Standard edition(Java ) programming Basics for beginner's
Java Standard edition(Java ) programming Basics  for beginner'sJava Standard edition(Java ) programming Basics  for beginner's
Java Standard edition(Java ) programming Basics for beginner's
momin6
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
PawanMM
 
Application Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience CourseApplication Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience Course
parag
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
Hitesh-Java
 
Object Oriented Methodology in Java (Lecture-1)
Object Oriented Methodology in Java (Lecture-1)Object Oriented Methodology in Java (Lecture-1)
Object Oriented Methodology in Java (Lecture-1)
Md. Mujahid Islam
 
Core java
Core javaCore java
Core java
sharad soni
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
BalamuruganV28
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
Anton Keks
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
OmegaHub
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Professional Guru
 
Introduction To Java Programming_ A Beginner's Guide_16_06_23.pdf
Introduction To Java Programming_ A Beginner's Guide_16_06_23.pdfIntroduction To Java Programming_ A Beginner's Guide_16_06_23.pdf
Introduction To Java Programming_ A Beginner's Guide_16_06_23.pdf
vibinjackson
 
Eclipse Training - Introduction
Eclipse Training - IntroductionEclipse Training - Introduction
Eclipse Training - Introduction
Luca D'Onofrio
 
JAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdfJAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdf
Prof. Dr. K. Adisesha
 

Similar to Java Course 11: Design Patterns (20)

Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
JavaFX in Action Part I
JavaFX in Action Part IJavaFX in Action Part I
JavaFX in Action Part I
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Java Standard edition(Java ) programming Basics for beginner's
Java Standard edition(Java ) programming Basics  for beginner'sJava Standard edition(Java ) programming Basics  for beginner's
Java Standard edition(Java ) programming Basics for beginner's
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
Application Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience CourseApplication Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience Course
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Object Oriented Methodology in Java (Lecture-1)
Object Oriented Methodology in Java (Lecture-1)Object Oriented Methodology in Java (Lecture-1)
Object Oriented Methodology in Java (Lecture-1)
 
Core java
Core javaCore java
Core java
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Introduction To Java Programming_ A Beginner's Guide_16_06_23.pdf
Introduction To Java Programming_ A Beginner's Guide_16_06_23.pdfIntroduction To Java Programming_ A Beginner's Guide_16_06_23.pdf
Introduction To Java Programming_ A Beginner's Guide_16_06_23.pdf
 
Eclipse Training - Introduction
Eclipse Training - IntroductionEclipse Training - Introduction
Eclipse Training - Introduction
 
JAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdfJAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdf
 

More from Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
Anton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Anton Keks
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
Anton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
Anton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
Anton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
Anton Keks
 

More from Anton Keks (16)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 

Recently uploaded (20)

From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 

Java Course 11: Design Patterns

  • 1. Java course - IAG0040 Design Patterns Anton Keks 2011
  • 2. The Increasing Complexity Complexity of software systems Time New programming paradigms Higher level of abstraction HW Assembler Structural P. (DSL, AOP?) CPUs Procedural P. OOP ... Java course – IAG0040 Lecture 11 Anton Keks Slide 2
  • 3. The emerge of OOP ● Response to complexity ● Software crisis: difficulty of writing correct, understandable, and verifiable programs ● Emphasizes modularity & reusability ● Solves the “Tramp Data” problem ● Closer to the Real World ● Program == cooperating objects, not a list of instructions Java course – IAG0040 Lecture 11 Anton Keks Slide 3
  • 4. What are design patterns? ● Anywhere in the world you can find recurring patterns ● Design patterns – are building blocks of a system's architecture – are recurring solutions to design problems that you see over – identify and specify abstractions that are above the level of single classes and instances Java course – IAG0040 Lecture 11 Anton Keks Slide 4
  • 5. Where do they come from? ● First referenced in early 80's, with the emerge of OOP ● Formally defined in 1994 in the GOF book (even before Java!) ● Hundreds more have been identified since then ● Are usually discovered (through pattern- mining) rather than invented Java course – IAG0040 Lecture 11 Anton Keks Slide 5
  • 6. GOF (Gang of Four) book ● Title: Design Patterns: Elements of Reusable Object-Oriented Software ● Is the first and essential book on patterns ● Patterns are well classified and described ● Every professional software developer must know them Java course – IAG0040 Lecture 11 Anton Keks Slide 6
  • 7. MVC ● Model-View-Controller ● One of the first patterns, comes from Smalltalk language ● Is a “best practice” of splitting GUI applications into – Model - holds/stores data and provides data access interface – View - displays data to the user obtained from the model – Controller - manipulates the model, selects appropriate views ● Therefore, the code consists of three decoupled layers, which can work together or independently ● Any of the layers can be modified/rewritten without modifications to other layers Java course – IAG0040 Lecture 11 Anton Keks Slide 7
  • 8. Pattern classification ● The GOF book defines 3 major types of patterns: – Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case. – Structural patterns help you compose groups of objects into larger structures, such as complex user interfaces or accounting data. – Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program. Java course – IAG0040 Lecture 11 Anton Keks Slide 8
  • 9. Anti-patterns ● This term is also widely used to define certain patterns, which should be avoided in software design ● Anti-patterns (aka pitfalls) are commonly reinvented bad solutions to problems ● Knowing anti-patterns is as important as knowing patterns ● Another term used in Agile Software Development is code smell (eliminated by refactoring) ● See Wikipedia articles on both Anti-pattern and Code smell for more info and examples Java course – IAG0040 Lecture 11 Anton Keks Slide 9
  • 10. Software Design vs Architecture ● Software design is the structure of code and relations between its elements (classes) ● Software architecture is the same as software design, but used when people want to make it look important (after Martin Fowler) – Architecture is the part of design that is difficult to change – Therefore it is undesired :-) Java course – IAG0040 Lecture 11 Anton Keks Slide 10
  • 11. Some design considerations ● Thinking about design is very important at all stages during a project. If it needs corrections then refactoring should be used ● Consistent API and loosely coupled code are very important - they make changes easy ● Unit tests and TDD help a lot ● Design patterns help make your design better and more understandable to others Java course – IAG0040 Lecture 11 Anton Keks Slide 11
  • 12. General concepts of design ● Fundamental reason for patterns: keep classes separated, prevent them from knowing too much about each other ● Abstract classes and interfaces are major tools ● Program to interfaces, not to implementations ● Prefer object composition to inheritance; it usually results in cleaner code (this is simply a construction of objects that contain others) – Delegation may be used for reusing “parent” behavior Java course – IAG0040 Lecture 11 Anton Keks Slide 12
  • 13. Iterator ● Behavioral pattern, synonym: Cursor ● You already know it from the Collections API! ● Iterator provides a way for accessing elements of an aggregate object sequentially without exposing its underlying representation ● Iterator is a special object provided by an aggregate object for holding of iteration state – better than if aggregate objects change their state during iteration (e.g. provide their own next() methods) – better than index-based element access - hides implementation details – several iterators may be used at once on the same data Java course – IAG0040 Lecture 11 Anton Keks Slide 13
  • 14. Lazy Initialization ● The idea is to initialize “expensive” objects on demand, e.g. only when they are accessed (this is sometimes referred to as “caching”) – if expensive object is never accessed then it is never created ● If initialization takes time and several threads access the object, then synchronization is needed ● Double-checked locking is a clever (but broken) trick: – public Object getExpensiveObject() { if (instance == null) { synchronized (this) { if (instance == null) instance = new ... } } return instance; } Java course – IAG0040 Lecture 11 Anton Keks Slide 14
  • 15. Singleton ● Creational pattern, sometimes uses lazy initialization ● Ensures a class has only one instance, and provides global access point to it ● public class Singleton { private Singleton() {} // private constructor private static Singleton uniqueInstance = new Singleton(); public static Singleton getInstance() { return uniqueInstance; // can be lazily initialized } } Java course – IAG0040 Lecture 11 Anton Keks Slide 15
  • 16. Singleton (2) ● Better than global variables (controlled access, doesn't pollute namespace) ● More flexible than class operations (static methods): can be polymorphic and subclassed, permits easy design changes, etc ● Disadvantages: may result in coupled code, if used directly too much. Difficult to mock in unit tests ● (better alternative – use singletons in an IoC container, like PicoContainer or Spring) Java course – IAG0040 Lecture 11 Anton Keks Slide 16
  • 17. Factory Method ● Creational pattern, synonyms: Factory, Virtual Constructor ● Defines an interface for creating an object of particular abstract type, but lets subclasses decide which concrete class to instantiate ● Used by many modern frameworks and APIs (e.g. SAXParserFactory) ● public class BulldogFactory implements DogFactory { public Dog createDog() { return new Bulldog(); } } ● public class DachshundFactory implements DogFactory { public Dog createDog() { return new Dachshund(); } } Java course – IAG0040 Lecture 11 Anton Keks Slide 17
  • 18. Factory Method (2) ● Allows writing of polymorphic code that can work with different implementations of interfaces without any direct references to them, eliminates hardcoding of implementation class names ● The method must be non-static, if you want to override it in a superclass of factory ● Variation: factory method can be static and decide itself what to instantiate – using configuration – with the help of parameters Java course – IAG0040 Lecture 11 Anton Keks Slide 18
  • 19. Abstract Factory ● Creational pattern, synonym: Kit ● Provides an interface for creating families of related or dependent objects without specifying their concrete classes ● Abstract Factory is similar to Factory Method with the exception that methods are never static and Factories are always subclassed in order to return different sets of instances Java course – IAG0040 Lecture 11 Anton Keks Slide 19
  • 20. Abstract Factory (2) ● Example: GUI toolkit with Factories for creation of widgets with different look and feel ● public interface AbstractWidgetFactory { public Button createButton(); public ScrollBar createScrollBar(); } public class MotifLookAndFeelWidgetFactory implements AbstractWidgetFactory { ... } Java course – IAG0040 Lecture 11 Anton Keks Slide 20
  • 21. Builder ● Creational pattern ● Eliminates 'telescoping' constructors – without sacrificing immutability – has all advantages of Factory ● Create Builder inner static class with methods returning 'this' and build() method returning the class instance ● Pizza pizza = new Pizza.Builder(). withOnion().doubleCheese().build(); ● Very readable, better than infinite number of constructors with boolean or numeric arguments, or setters Java course – IAG0040 Lecture 11 Anton Keks Slide 21
  • 22. Common structural patterns ● Decorator ● Adapter ● Composite ● (Proxy) Java course – IAG0040 Lecture 11 Anton Keks Slide 22
  • 23. Decorator ● Structural pattern, synonym: Wrapper ● Attach additional responsibilities to an object dynamically. ● Decorators provide a flexible alternative to subclassing for extending functionality ● Useful for adding responsibilities dynamically to objects, not classes. ● Decorator must have the same interface as the decorated object. Java course – IAG0040 Lecture 11 Anton Keks Slide 23
  • 24. Decorator (2) ● Decorator delegates all method calls to wrapped instance and does something else before or after. Every object can be decorated several times. ● BufferedInputStream decorates any InputStream ● public class LoggingConnection implements Connection { private Connection conn; ... public boolean isActive() { System.out.println(“isActive was called!”); return conn.isActive(); } ... } Java course – IAG0040 Lecture 11 Anton Keks Slide 24
  • 25. Adapter ● Structural pattern, synonym: Wrapper ● Converts the interface of a class into another interface clients expect ● Adapter lets classes work together that couldn't otherwise because of incompatible interfaces Java course – IAG0040 Lecture 11 Anton Keks Slide 25
  • 26. Adapter (2) ● In other words, Adapter just translates requests to another API of the wrapped class ● Examples – InputStreamReader adapts an InputStream to the Reader interface – Arrays.asList() represents java arrays as List instances – Collections.enumeration() represents Iterators as Enumerations Java course – IAG0040 Lecture 11 Anton Keks Slide 26
  • 27. Composite ● Structural pattern, similar to Decorator ● Composes objects into tree structures to represent part-whole hierarchies ● Composite lets clients treat individual objects and compositions of objects uniformly Java course – IAG0040 Lecture 11 Anton Keks Slide 27
  • 28. Composite (2) ● Example: in a GUI toolkit, a Window is a composite of other Widgets, while is a Widget itself ● Many GUI toolkits have base classes named Composite, which can have a layout manager assigned and an arbitrary number of child Composites ● SequenceInputStream is a composite of many InputStreams Java course – IAG0040 Lecture 11 Anton Keks Slide 28
  • 29. Proxy ● Decorator, Adapter, and Composite – any of them can be called 'Proxy' ● Proxy is a class, functioning as an interface to another thing ● In a more specific sense (Virtual Proxy): wrapping classes can – control access to wrapped objects – lazily initialize the delegates inside them Java course – IAG0040 Lecture 11 Anton Keks Slide 29
  • 30. Strategy ● Behavioral pattern, synonym: Policy ● Defines a family of algorithms, encapsulates each one, and makes them interchangeable; eliminates conditions from the code (GoF) ● Capture the abstraction in an interface, bury implementation details in derived classes ● Strategy lets the algorithm vary independently from clients that use it – Algorithms can be changed on-the-fly at runtime Java course – IAG0040 Lecture 11 Anton Keks Slide 30
  • 31. Strategy (2) ● Strategy pattern allows adding of new algorithms easily and/or dynamically ● Participants: – Strategy – an interface or abstract class of all strategies – ConcreteStrategy – each is a different implementation of Strategy – Context – a class, initialized to use and maintain a ConcreteStrategy, can provide additional (context specific) data to it Java course – IAG0040 Lecture 11 Anton Keks Slide 31
  • 32. State ● Behavioral pattern, similar to Strategy ● Each “Strategy” is one of the states of the Context – Strategy usually represents a single abstraction – each State can implement several behaviors (different actions, methods) – State interface may as well provide methods for transitions in order to implement a Finite State Machine Java course – IAG0040 Lecture 11 Anton Keks Slide 32
  • 33. Façade ● Structural pattern ● Provides a unified interface to a set of interfaces in subsystem ● Facade defines a higher-level interface that makes the subsystem easier to use ● Structuring a system into subsystems reduces complexity. Then subsystems can communicate only through Facades, while using their own lower-level interfaces internally. This reduces coupling ● Example: consider internals of a compiler: it can have classes like Scanner, Parser, ProgramNode, BytecodeStream, etc, but externally you use the Facade class named Compiler, which simply takes input file and produces an output file ● Facade just delegates requests to appropriate subsystem classes, it doesn't do anything itself Java course – IAG0040 Lecture 11 Anton Keks Slide 33
  • 34. Prototype ● Creational pattern ● Specifies the kind of objects to create using the prototypical instance – creates new objects by copying (cloning) the prototype ● Allows having an initialized reference instance of some abstract class, then it can be cloned or recreated with reflection API for creation of new objects ● Useful when creating new instances is too complex (and slow) or less convenient than cloning ● Convenient for implementation of plug-in architectures, where implementations may be added/removed dynamically Java course – IAG0040 Lecture 11 Anton Keks Slide 34
  • 35. Observer ● Behavioral pattern, synonym: Publish- Subscribe ● Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically ● Provides decoupled classes, which can work together or independently Java course – IAG0040 Lecture 11 Anton Keks Slide 35
  • 36. Observer (2) ● Participants: – Subject (Observable) – the data to observe – Observer – an updating interface for objects, which are notified – ConcreteSubject – sends notifications to all registered ConcreteObservers – ConcreteObserver – knows about ConcreteSubject, updates itself on notifications ● Java provides both Observable abstract class and Observer interface Java course – IAG0040 Lecture 11 Anton Keks Slide 36