Basic Design Patterns 1. Introduction Gabriel Mañana Ed. 453 Of. 120 Ext. 14080 gjmananag...
-
date post
22-Dec-2015 -
Category
Documents
-
view
214 -
download
0
Transcript of Basic Design Patterns 1. Introduction Gabriel Mañana Ed. 453 Of. 120 Ext. 14080 gjmananag...
Basic Design PatternsBasic Design Patterns
1. Introduction
Gabriel MañanaEd. 453 Of. 120 Ext. 14080
gjmananag @unal.edu.co
Basic Design PatternsBasic Design Patterns
1. IntroductionWhat is a Design Pattern?Design Patterns in MVCDescribing Design PatternsCatalog of Design PatternsSolving Design ProblemsSelecting Design PatternsUsing Design Patterns
Basic Design PatternsBasic Design Patterns
Designing OO software is hard
Designing reusable OO software is even harder
Basic Design PatternsBasic Design Patterns
1. Find pertinent objects
2. Factor objects into classes
3. Define class interfaces
4. Define inheritance hierarchies
5. Establish key relationships
Basic Design PatternsBasic Design Patterns
The design should be specific to the problem at hand but also general enough to address future problems and requirements:
avoid redesign
Basic Design PatternsBasic Design Patterns
The difference between expert and novice designers is experience:
Recurring patterns of classes and communicating objects.
Basic Design PatternsBasic Design Patterns
These patterns solve specific design problems and make OO designs more flexible:
reusable
Basic Design PatternsBasic Design Patterns
Each design pattern systematically names, explains and evaluates an important and recurring design in OO systems.
Basic Design PatternsBasic Design Patterns
Christopher Alexander:
“Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.”
Basic Design PatternsBasic Design Patterns
Essential pattern elements:
1. pattern name
2. problem
3. solution
4. consequences
Basic Design PatternsBasic Design Patterns
1. Pattern Name:
Let us design at a higher level of abstraction.
Basic Design PatternsBasic Design Patterns
2. Problem:
Explains the problem and its context.
describes when to apply the pattern
Basic Design PatternsBasic Design Patterns
3. Solution:
Describes the elements that make up the design, their relationships, responsibilities and collaborations.
Basic Design PatternsBasic Design Patterns
4. Consequences:
Are the results and trade-offs of applying the pattern, its impact on a system’s flexibility, extensibility or portability
Basic Design PatternsBasic Design Patterns
Level of Abstraction?
Description of communicating objects and classes that are customized to solve a general design problem in a particular context.
Basic Design PatternsBasic Design Patterns
The design pattern identifies the participating classes and instances, their roles and collaborations, and the distribution of responsibilities.
Basic Design PatternsBasic Design Patterns
It describes when it applies, whether it can be applied in view of other design constraints, and the consequences and trade-offs of its use. (code)
Smalltalk MVCSmalltalk MVC
Model/View/Controller
Triad of classes used to build user interfaces
pattern
Smalltalk MVCSmalltalk MVC
Model: application object
View: its screen presentation
Controller: describes the way the UI reacts to user input
Smalltalk MVCSmalltalk MVC
MVC: Decouples views and models by establishing a subscribe/notify protocol between them.
(Observer Pattern)
Smalltalk MVCSmalltalk MVC
In MVC views can be nested: CompositeView, subclass of View.
(Composite Pattern)
Smalltalk MVCSmalltalk MVC
MVC also allows to change the way a view responds to user input without changing its visual presentation.
(Controller Pattern)
Smalltalk MVCSmalltalk MVC
View-Controller relationship is an example of the Strategy design pattern.
(Strategy Pattern: an object that represents an algorithm)
Smalltalk MVCSmalltalk MVC
MVC main relationships:
Observer
Composite
Strategy
Describing Design PatternsDescribing Design Patterns
Pattern Name
The pattern’s name conveys the essence of the pattern succintly.
Describing Design PatternsDescribing Design Patterns
IntentWhat does the design pattern do?
What is the rationale and intent?
What particular design issue or
problem does it address?
Describing Design PatternsDescribing Design Patterns
Also Known As
Other well-known names for the pattern, if any.
Describing Design PatternsDescribing Design Patterns
Motivation
A scenario that illustrates a design problem and how the class and object structures in the pattern
solve the problem.
Describing Design PatternsDescribing Design Patterns
ApplicabilityWhat are the situations in which the design pattern can be applied?
What are examples of poor designs that the pattern can address?
Describing Design PatternsDescribing Design Patterns
StructureA graphical representation of the classes in the pattern using a notation based on the Unified Modeling Language (UML).
Interaction diagrams are also used to illustrate sequences of request and collaborations between objects.
Describing Design PatternsDescribing Design Patterns
Participants
The classes and/or objects participating in the design pattern and their responsibilities.
Describing Design PatternsDescribing Design Patterns
Collaborations
How the participants collaborate to carry out their responsibilities.
Describing Design PatternsDescribing Design Patterns
Consequences What are the trade-offs and results of using the pattern?
What aspect of system structure does it let vary independently?
Describing Design PatternsDescribing Design Patterns
Implementation What pitfalls, hints or techniques should you be aware of when implementing the pattern?
Are there language-specific issues?
Describing Design PatternsDescribing Design Patterns
Sample Code
Code fragments that illustrate how you might implement the pattern.
Describing Design PatternsDescribing Design Patterns
Known UsesExamples of the pattern found in real systems.
At least two examples from different domains.
Describing Design PatternsDescribing Design Patterns
Related Patterns What design patterns are closely related to this one?
What are the important differences?
With other patterns should this one be used?
Catalog of Design PatternsCatalog of Design Patterns
Abstract Factory
Provide an interface for creating families of related/dependent objects without specifying their
concrete classes.
Catalog of Design PatternsCatalog of Design Patterns
Adapter
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of imcompatible interfaces.
Catalog of Design PatternsCatalog of Design Patterns
Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
Catalog of Design PatternsCatalog of Design Patterns
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Catalog of Design PatternsCatalog of Design Patterns
Chain of ResponsibilityAvoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Catalog of Design PatternsCatalog of Design Patterns
Command
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Catalog of Design PatternsCatalog of Design Patterns
Composite
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Catalog of Design PatternsCatalog of Design Patterns
Decorator
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Catalog of Design PatternsCatalog of Design Patterns
Façade
Provide a unified interface to a set of interfaces in a subsystem. Facades define a higher-level interface that makes the subsystem easier to use.
Catalog of Design PatternsCatalog of Design Patterns
Factory Method
Define an interface for creating an object, but let subclasses decide which class instantiate. Factory Method lets a class defer instantiation to subclasses.
Catalog of Design PatternsCatalog of Design Patterns
Flyweight
Use sharing to support large number of fine-grained objects efficiently.
Catalog of Design PatternsCatalog of Design Patterns
Interpreter
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Catalog of Design PatternsCatalog of Design Patterns
Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Catalog of Design PatternsCatalog of Design Patterns
MediatorDefine an object that encapsulates how a set of objects interact. Mediators promote loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Catalog of Design PatternsCatalog of Design Patterns
Memento
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Catalog of Design PatternsCatalog of Design Patterns
Observer
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Catalog of Design PatternsCatalog of Design Patterns
Prototype
Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
Catalog of Design PatternsCatalog of Design Patterns
Proxy
Provide a surrogate or placeholder for another object to control access to it.
Catalog of Design PatternsCatalog of Design Patterns
Singleton
Ensure a class has only one instance, and provide a global point to access to it.
Catalog of Design PatternsCatalog of Design Patterns
State
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Catalog of Design PatternsCatalog of Design Patterns
StrategyDefine a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Catalog of Design PatternsCatalog of Design Patterns
Template MethodDefine the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algoritm without changing the algorithm's structure.
Catalog of Design PatternsCatalog of Design Patterns
VisitorRepresent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Catalog of Design PatternsCatalog of Design Patterns
1. Purpose:
Creational
Structural
Behavioral
Catalog of Design PatternsCatalog of Design Patterns
2. Scope:
Class (static)
Object (dynamic)
Design Patterns SpaceDesign Patterns SpacePurpose
Creational Structural Behavioral
Scope Class Factory Method Adapter (class) Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter (obj)
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Solving ProblemsSolving Problems
Finding appropiate objects
Determining object granularity
Specifying object interfaces
Specifying object implementations
Class vs. Interface inheritance
Solving ProblemsSolving Problems
ClassName
operation1()Type operation2()...
instanceVariable1Type instanceVariable2...
AbstractClass
operation1()Type operation2()...
Solving ProblemsSolving Problems
ParentClass
operation()...
Instantiator
SubClass
Instantiatee
Solving ProblemsSolving Problems
AbstractClass
operation()
ConcreteSubClass
operation()implementationpseudocode
Solving ProblemsSolving Problems
Programming to an Interface,not an Implementation
Inheritance vs. Composition
Delegation
Inheritance vs. Parameterized Types
Solving ProblemsSolving Problems
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
1. Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface the clients expect.
2. Clients remain unaware of the specific classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
Solving ProblemsSolving Problems
This so greatly reduces implementation dependencies between subsystems that it leads to the following principle of Object Oriented Design:
Program to an interface, not an implementation
Solving ProblemsSolving Problems
Inheritance vs. Composition
There are two common techniques for reusing functionality in object oriented systems:
1. class inheritance
2. object composition
Solving ProblemsSolving Problems
Class Inheritance:
Lets you define the implementation of one class in terms of another’s.
Reuse by subclassing is often referred to as white-box reuse. The term white-box refers to visibility: with inheritance, the internals of parent classes are often visible to subclasses.
Solving ProblemsSolving Problems
Object Composition:
Here, new functionality is obtained by assembling or composing objects to get more complex functionality.
This style of reuse is called black-box reuse, because no internal details of objects are visible.
Solving ProblemsSolving Problems
Inheritance:
Straightforward to use, since it’s supported directly by the programming language
Makes it easier to modify the implementation being used (method overriding)
Solving ProblemsSolving Problems
Inheritance:
You can’t change the implementations inherited from parent classes at run-time, because inheritance is defined at compile-time
Because inheritance exposes a subclass to details of it’s implementation, it’s often said that “inheritance breaks encapsulation”
Solving ProblemsSolving Problems
Object Composition:
Object composition is defined dynamically at run-time through objects acquiring references to other objects (Abstract Factory, Builder, …)
No encapsulation broken (interfaces)
Any object can be replaced at run-time as long as it has the same type
Solving ProblemsSolving Problems
Object Composition:
Favoring object composition over class inheritance helps you keep each class encapsulated and focused on one task.
Your classes and class hierarchies will remain small
A design based on object composition will have more objects
Solving ProblemsSolving Problems
Second principle of Object Oriented Design:
Favor object composition over class
inheritance
Solving ProblemsSolving Problems
Delegation
Delegation is a way of making composition as powerful for reuse as inheritance.
Solving ProblemsSolving Problems
The receiving object delegates operations to its delegate.
This is similar to subclasses deferring operations to parent classes
The receiver passes itself (this) to the delegate, to let the delegated operation refer to the receiver
Solving ProblemsSolving Problems
Window
area()
Rectangle
area()
widthheight
return width*height
return rect->area()
rect
Solving ProblemsSolving Problems
Delegation has a disadvantage it shares with other techniques that make software more flexible through object composition:
dynamic, highly parameterized software is harder to understand than more static software.
Solving ProblemsSolving Problems
Several design patterns use delegation:
State
Strategy
Visitor
Mediator
Chain of Responsibility
Bridge
Solving ProblemsSolving Problems
Inheritance vs. Paremeterized Types
Another technique for reusing functionality in object oriented systems is trough parameterized types:
This technique lets you define a type without specifying all the other types it uses
The unspecified type is supplied at the point of use
Solving ProblemsSolving Problems
Inheritance vs. Paremeterized Types
Parameterized types give a third way to compose behavior in object oriented systems:
Solving ProblemsSolving Problems
Inheritance vs. Paremeterized Types
To parameterize a sorting routine by the operation it uses to compare elements, we could make the comparison
1. An operation implemented by subclasses (Template Method)
2. The responsibility of an object that’s passed to the sorting routine (Strategy)
3. An argument of a C++ template or Java parameterized type
Solving ProblemsSolving Problems
Parameterized Type Example
List<Integer> integerList = new LinkedList<Integer>()
Map<String, Integer> integerMap = new HashMap<String, Integer>()
Solving ProblemsSolving Problems
Generic Class Example
public class C<T1, T2> {
private T1 type1;
private T2 type2;
public C( T1 type1, T2 type2 ) {
this.type1 = type1;
this.type2 = type2;
}
Solving ProblemsSolving Problems
Generic Class Example
...
public T1 getType1() {
return this.type1;
}
public T2 getType2() {
return this.type2;
}
Solving ProblemsSolving Problems
Generic Class Example
public static void main(String args[]) {
C<String, Integer> cStrInt = new C<String, Integer>("one", 1);
C<Integer, Boolean> cIntBool = new C<Integer, Boolean>(1, true);
}
Solving ProblemsSolving Problems
Generic Interface Example
public interface I<T> {
public T getConnectionPool();
public void releaseConnectionPool(
T connPool );
}
Solving ProblemsSolving Problems
Generic Method Examplepublic class M {
public static <T extends Comparable> T
minimum( T a, T b )
{ if (a.compareTo( b ) <= 0)
return a;else
return b; }
}
Designing for ChangeDesigning for Change
The key to maximizing reuse lies in anticipating new requirements and changes, and in designing your systems so that they can evolve accordingly.
Designing for ChangeDesigning for Change
Common causes of redesign:
1.Creating an object by specifying a class explicitly
(Abstract Factory)
(Factory Method)
(Prototype)
Designing for ChangeDesigning for Change
Common causes of redesign:
2.Dependence on specific operations
(Chain of Responsibility)
(Command)
Designing for ChangeDesigning for Change
Common causes of redesign:
3.Dependence on hardware and software platform
(Abstract Factory)
(Bridge)
Designing for ChangeDesigning for Change
Common causes of redesign:
4.Dependence on object implementations or representations
(Abstract Factory) (Bridge)
(Memento) (Proxy)
Designing for ChangeDesigning for Change
Common causes of redesign:
5.Algorithmic dependences
(Builder) (Iterator)
(Strategy) (Template Method)
(Visitor)
Designing for ChangeDesigning for Change
Common causes of redesign:
6.Tight coupling
(Abstract Factory) (Bridge)
(Chain of Responsibilty) (Command)
(Facade) (Mediator) (Observer)
Designing for ChangeDesigning for Change
Common causes of redesign:
7.Extending functionality by subclassing
(Bridge) (Chain of Responsibilty)
(Composite) (Decorator)
(Observer) (Strategy)
Designing for ChangeDesigning for Change
Common causes of redesign:
8. Inability to alter classes conveniently
(Adapter)
(Decorator)
(Visitor)
ToolkitsToolkits
A set of related and reusable classes designed to provide useful, general purpose functionality.
(C++ iostream, STL)(java.lang/java.util)
ToolkitsToolkits
Toolkits emphasize code reuse
The OO equivalent of subroutine libraries
FrameworksFrameworks
A set of cooperating classes that make up a reusable design for a specific class of software.
(C++ MFC)(J2EE)
FrameworksFrameworks
The framework dictates the architecture of the application
Defines the overall structure, its partitioning into classes and objects, the key responsibilities, and the collaboration patterns
Design Difficulty LevelsDesign Difficulty Levels
1.Applications
2.Toolkits (harder)
3.Frameworks (hardest)
Selecting Design PatternsSelecting Design Patterns
Consider how design patterns solve design problems
Scan intent sections
Study how patterns interrelate
Study patterns of like purpose
Selecting Design PatternsSelecting Design Patterns
Examine a cause of redesign
Consider what should be variable in the design
Using Design PatternsUsing Design Patterns
Read the pattern once through
Pay particular attention to the Applicability and Consequences sections to ensure the pattern is right for the problem.
Using Design PatternsUsing Design Patterns
Study the Structure, Participants and Collaboration sectionsMake sure you understand the classes and objects in the pattern and how they relate to one another.
Using Design PatternsUsing Design Patterns
Look at the Sample Code section to see a concrete exampleStudying the code helps you learn how to implement the pattern.
Using Design PatternsUsing Design Patterns
Choose Names for pattern participants that are meaningful in the application contextThe names for particpants in design patterns are usually too abstract to appear in an application.
Using Design PatternsUsing Design Patterns
Define the Classes
Declare their interfaces, establish their inheritance relationships, and define the instance variables that represent data and object references.
Using Design PatternsUsing Design Patterns
Define application specific names for operations in the patternUse the responsibilities and collaborations associated with each operation as a guide.
Using Design PatternsUsing Design Patterns
Implement the operations to carry out the responsibilities and collaborations in the patternThe examples in the sample code section can help.