Java Course 11: Design Patterns
-
Upload
anton-keks -
Category
Technology
-
view
2.374 -
download
2
description
Transcript of Java Course 11: Design Patterns
Design PatternsDesign Patterns
Java course - IAG0040Java course - IAG0040
Anton Keks 2011
Lecture 11Lecture 11Slide Slide 22
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
The Increasing ComplexityThe Increasing Complexity
Time
Complexity of software systems
New programming paradigmsHigher level of abstraction
HW Assembler Structural P. (DSL, AOP?) CPUs Procedural P. OOP ...
Lecture 11Lecture 11Slide Slide 33
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
The emerge of OOPThe 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
Lecture 11Lecture 11Slide Slide 44
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
What are design patterns?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
Lecture 11Lecture 11Slide Slide 55
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Where do they come from?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
Lecture 11Lecture 11Slide Slide 66
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
GOF (Gang of Four) bookGOF (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
Lecture 11Lecture 11Slide Slide 77
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
MVCMVC● 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
Lecture 11Lecture 11Slide Slide 88
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Pattern classificationPattern 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.
Lecture 11Lecture 11Slide Slide 99
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Anti-patternsAnti-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
Lecture 11Lecture 11Slide Slide 1010
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Software Design vs ArchitectureSoftware 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 :-)
Lecture 11Lecture 11Slide Slide 1111
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Some design considerationsSome 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
Lecture 11Lecture 11Slide Slide 1212
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
General concepts of designGeneral 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
Lecture 11Lecture 11Slide Slide 1313
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
IteratorIterator● 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
Lecture 11Lecture 11Slide Slide 1414
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Lazy InitializationLazy 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;
}
Lecture 11Lecture 11Slide Slide 1515
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
SingletonSingleton
● 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 constructorprivate static Singleton uniqueInstance =
new Singleton();public static Singleton getInstance() {
return uniqueInstance; // can be lazily initialized
}}
Lecture 11Lecture 11Slide Slide 1616
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Singleton (2)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)
Lecture 11Lecture 11Slide Slide 1717
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Factory MethodFactory 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(); } }
Lecture 11Lecture 11Slide Slide 1818
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Factory Method (2)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
Lecture 11Lecture 11Slide Slide 1919
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Abstract FactoryAbstract 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
Lecture 11Lecture 11Slide Slide 2020
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Abstract Factory (2)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 {...
}
Lecture 11Lecture 11Slide Slide 2121
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
BuilderBuilder
● 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
Lecture 11Lecture 11Slide Slide 2222
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Common structural patternsCommon structural patterns
● Decorator● Adapter● Composite● (Proxy)
Lecture 11Lecture 11Slide Slide 2323
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
DecoratorDecorator
● 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.
Lecture 11Lecture 11Slide Slide 2424
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Decorator (2)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();
}...
}
Lecture 11Lecture 11Slide Slide 2525
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
AdapterAdapter
● 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
Lecture 11Lecture 11Slide Slide 2626
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Adapter (2)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
Lecture 11Lecture 11Slide Slide 2727
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
CompositeComposite
● 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
Lecture 11Lecture 11Slide Slide 2828
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Composite (2)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
Lecture 11Lecture 11Slide Slide 2929
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
ProxyProxy
● 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
Lecture 11Lecture 11Slide Slide 3030
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
StrategyStrategy
● 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
Lecture 11Lecture 11Slide Slide 3131
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Strategy (2)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
Lecture 11Lecture 11Slide Slide 3232
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
StateState
● 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
Lecture 11Lecture 11Slide Slide 3333
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
FaçadeFaç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
Lecture 11Lecture 11Slide Slide 3434
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
PrototypePrototype
● 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
Lecture 11Lecture 11Slide Slide 3535
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
ObserverObserver
● 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
Lecture 11Lecture 11Slide Slide 3636
Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks
Observer (2)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