DesigningandDeveloping EnterpriseApplications(DDEA)
Lesson03DesignPatterns (Part01)
ByCrishanthaNanayakkara
DDEA Course Contents
(1)ObjectOrientation &UML (4)EnterpriseApplication Security
(2)PatternsinEnterprise ApplicationDevelopmentand Integration
Standard(GOF)Patterns WebLayerPatterns BusinessLayerPatterns DataAccessLayerPatterns EnterpriseIntegrationPatterns
DDEA DDEA
(5)EnterpriseApplication Implementation Strategies
(6)FutureTrends (3)ServiceOriented Architecture(SOA)
CloudComputing (SAAS,IAAS,PAAS)
The gap between the best software engineering practice and the average practice is very wide perhaps wider than the other engineering
Fred Brooks (A famous
author, ACM award winner)
What is a Pattern?
A pattern is a solution to a problem in a context Context : is the situation in which the pattern applies.
This should be a recurring situation
Problem : refers to the goal you are trying to achieve
in this context. But it also refers to any constraints that occur in the context
Solution : is what you are after: a general design that
anyone can apply which resolves the goal and the set of constraints
What is a Pattern?
This means, a Design Pattern gives you a solution to a common recurring design problem However, The Design Patterns are not meant to be laws or rules; they are just guidelines that you can even alter to fit to your needs
What are Pattern Catalogs?
The much formal way of specifying pattern descriptions
The first and the most definite Fundamental Design Pattern Catalog is GOF
(There are 23 fundamental patterns in it!!)
DesignPatterns:ElementsofReusable ObjectOrientedSoftware (AddisonWesley,1995)
CoreSecurityPatternCatalog
Reference:CoreSecurityPatterns
CoreJ2EEPatternCatalog
How to create your own design pattern?
Firstly, get the complete design pattern catalog and get familiar with them If you find a new pattern, then apply,
The Rule of Three
Pattern can be called a pattern if it has been applied in real world solution by at least three times
OO vs Design Patterns
Knowing the OO basics (abstraction, encapsulation, inheritance, polymorphism) will not make you a good designer!!!
Oh!!! Whatshould Idothen?
OO vs Design Patterns
Patterns show you how to build systems with good OO design qualities Patterns do not give you code. They give general solutions to design problems Patterns are not invented they are discovered
Fundamental Design Patterns (Gang Of Four - GOF)
GOF Design Pattern Organization
Tolearnpatternsfaster,theycanbeclassifiedas, PatternOrganization1(Whatpatterndoes)
CreationalProcessofobjectcreation BehavioralWaysclassesandobjectsinteractand distributeresponsibility StructuralCompositionofclassesandobjects
PatternOrganization2(Whetherapplytoclassesor objects)
ClassPatternsrelatedtoclasses,createdatcompiletime ObjectPatternsrelatedtoobjects,createdatruntime
GOF Design Pattern Organization - 1
GOF Design Pattern Organization - 1
Creational: Involve object initialization and provide a way to decouple client from the objects it needs to instantiate Structural:Lets you compose classes or objects into larger structures Behavioral: Concerned with how classes and objects interact or distribute responsibility
GOF Design Patterns (23 patterns)
Behavioral :
Strategy Observer Command Interpreter Iterator Mediator Memento Chain of Responsibility State Template Method Visitor
GOF Design Patterns (23 patterns)
Creational :
Abstract Factory Builder Factory Method Prototype Singleton
Structural :
Adapter Bridge Composite Decorator Facade Flyweight Proxy
GOF Design Pattern Organization - 2
GOF Design Pattern Organization - 2
Object: Describe relationship between objects. Patterns are typically created at runtime and more dynamic and flexible. Class: Describe relationship between classes. Patterns are typically created at compile-time.
Design Pattern Organization
Asshownintheabovetabletherearetwoadapters.Oneadapterpatterncanbeappliedtoabstractionof classwhileotherinabstractionofobject
GOF Design Pattern Relationships
Are patterns always great?
NO
Patterns are a tool, which only be used when it is needed Heavy use of patterns will lead to complexity Design patterns can be used as a shared vocabulary for communicating the design to others irrespective of the programming language
What are anti-patterns?
If a design pattern gives you a general solution to a recurring problem in a particular context then what does an anti-pattern give u?
An anti-pattern tells you how to go from a problem to a BAD solution
Why worry about finding anti-patterns?
To prevent other developers from making the same mistake
GOFDesign PatternAnalysis
StrategyPattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independentlyfromclientsthatuseit.
Design Principles covered - (3)
Design Principle 1
Identify the aspects of your application that vary and separate them from what stays the same
Design Principle 2
Program to an interface not to an implementation
Design Principle 3
Favor composition over inheritance
The Duck Simulation
Reference:HeadFirstDesignPatterns
How about Inheritance?
Thentheinheritedbehaviorwillbeattachedtoallinheritedclasseswhichdo nothavethatbehavior
How about an Interface?
Whats the one thing you always count on in software development?
CHANGE
Then,what happensifyou changeoneof thebehaviors?
Sincethereareno implementation codeininterfaces youhavetotrack downandchange allimplemented subclasses!!!!
Hmmm..... Ibadlyneeda design Patternnow!
Classroom Exercise (30 min)
Divide the class into 3 groups and each group need to come up with a design pattern to solve this issue related to the change of behaviors related to objects.
(P.Note: Each can group can come with their own example)
How to overcome this?
Design Principle 1
Identify the aspects of your application that vary and separate them from what stays the same
Means,
Take what varies and encapsulate it. So it will not effect the rest of your code This results,
Fewer consequences Adds flexibility
Separating behaviors
By separating behaviors from concrete classes, you will get the flexibility even change those behaviors with a minimal code change
In the previous example, if there are 10 sub classes extended or implemented the Flying behavior, you got to change all 10 sub classes if there is any change to the Flying behavior.
Separating behaviors
By separating behaviors from concrete classes, concrete classes will not need to know any implementation details of its own behaviors This approach is different to previous two approaches, which basically coupled the behavior to concrete classes
The behavior was implemented extending a super class The behavior was implemented providing a specialized interface to the sub class
Design Principle 2
Program to an interface, not an implementation
Does not mean a Java construct interfaces. This means a supertype However this is usually abstract class or an interface Doing this will create the opportunity to dynamic behavioral changes with the help of Polymorphism Programming to an implementation Dog dog = new Dog(); Programming to an interface / super type
Animal dog = new Dog();
How does this handle Reuse?
With this design other types of objects can reuse behaviors because they are no longer hidden away within concrete classes We are able to add new behaviors without modifying any of our existing concrete classes, which have these behaviors
Integrating the behavior
The behavior variables are declared as interface variable types performQuack() and performFly() replaces quack() and fly() PerformQuack() and performFly() methods delegates behavior implementations to the behavior classes
Design Principle 3
Favor composition over inheritance
When you put more than one class together as class variables that is called composition This has the Has-A relationship This gives a lot of flexibility Lets you encapsulate a family of algorithms into their own set of classes By doing this allows you to change the behavior runtime
Setting the behavior dynamically
Here any concrete class behavior can be changed dynamically by using the setter methods specified within the abstract class
Setting the behavior dynamically
Think of each set of behaviors as a family of algorithms These algorithms are interchangeable
Duck model = new ModelDuck(); model.performFly(); model.setFlyBehavior(new FlyRocketPowered()); model.performFly();
StrategyPatter n Defineafamilyofalgorithms,encapsulateeachone,andmakethem interchangeable.Strategyletsthealgorithmvaryindependentlyfrom clientsthatuseit.
Setting the behavior dynamically
Example: Duck Simulator
Reference:HeadFirstDesignPatterns
Example: Duck Simulator
Reference:HeadFirstDesignPatterns
Example: Duck Simulator
Reference:HeadFirstDesignPatterns
Example: Duck Simulator
Reference:HeadFirstDesignPatterns
ObserverPattern
Define a onetomany dependency between objects so that whenoneobjectchangesstate,allitsdependentsarenotified andupdatedautomatically.
Design Principles covered - (1)
Design Principle 4
Strive for loosely coupled designs between objects that interact
The Observer Pattern
Observer1
Observer2
Subscribers
Subject
Publisher
Observer3
When the in Subject changes, subscribers arenotified TheobserversaresubscribedtotheSubject to receive updates when the Subject data changes
Unsubscribed
The Observer Pattern
The subject and the observers are having a one to many relationship The observers are dependent on the subject When the subject state changes, the observers get notified In the observer pattern, (About the state)
Subject is the object that contains the state and it owns it Observers use it but do not own it
The Observer Pattern - Explained
Subject: Maintains a list of Observer references. Subject also
provides an interface for attaching and detaching Observer objects.
Observer: Defines an updating interface for objects that
should be notified of changes in a subject.
ConcreteSubject:
Stores state of interest to ConcreteObserver objects and sends notifications to its observers upon state changes.
ConcreteObserver:
Maintains a reference to a ConcreteSubject object and a state that should stay consistent with the subject's.
The Observer Pattern - Explained
The only thing the subject knows about an observer is that it implements a certain interface (The observer interface) Observers can be added to the system at any time No need to modify the subject to add new observers It means, the subject and the observers are very loosely coupled
Design Principle 4 Strive for loosely coupled designs between objects that interact Loosely coupled designs allow us to build flexible Object Oriented systems that can handle change How?
Because they minimize the interdependency between objects
An Example
An Example
Thisiswherethesubjecttellsalltheobservers aboutitsstate.Sincealltheobservers implementtheupdatemethoditiseasyto notifythem
CommandPattern
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests,andsupportundoableoperations
Concrete Command Objects Invoker Receiver
Client
Invoker
Command
Receiver
Concrete Command
CommandandConcreteCommand
Receiver
Invoker
Client
References
Head First Design Patterns: by Eric Freeman & Elisabeth Freeman Design Patterns: Elements of Reusable Object Oriented Software: Erich Gamma, Richard Helm, Ralph Johnson & John Vilssides (GOF) (http://www.hillside.net) Core Security Patterns: Best Practices and Strategies J2EE Web Services and Identity Management: Chris Steel, Ramesh Nagappan, Ray Lai, Sun Microsystems Core J2EE Patterns, Best Practices and Design Strategies: Deepak Alur, John Crupi, Dan Malks, 2nd Edition, Prentice Hall/ Sun Microsystems, 2003 http://www.javaworld.com/jw-11-1998/jw-11-techniques.html