l05 design patterns
DESCRIPTION
Hönnunarmunstur er þekktar og reyndar lausnir við almennum vandamálum. Hugbúnaðargerð felur í sér að leysa vandamál og oft rekumst við að sömu vandamálin aftur og aftur. Þessi vandamál má leysa með þekktum leiðum, svo kölluðum munstrum. Hönnunarmunstur skjala þekktar lausnir. Þau eru byggð á þekkingu úr iðnaðnum, segja hvað virkar og af hverju. Í þessum fyrirlestri skoðum við hönnunarmunstur, sögu þeirra og hvernig þau eru skjöluð. Við lítum á ýmis dæmi og tökum svo fyrir grunnmunstur - base patterns. Þá skoðum við Open Close Principle sem er eitt af þessum prinsippum sem við þurfum að hafa í huga.TRANSCRIPT
![Page 1: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/1.jpg)
Lecture 05Design Patterns
![Page 2: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/2.jpg)
Agenda Patterns
– History, classification, structure Design Principles
– Loosley Coupled Design Principle– Open-Close Principle
Base Patterns
![Page 3: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/3.jpg)
Reading Design Patterns Observer pattern Factory pattern Base Patterns The Open-Closed Principle
![Page 4: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/4.jpg)
Patterns
![Page 5: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/5.jpg)
Design Patterns Design pattern is a general solution to a
common problem in software design– Systematic approach for problems that reoccur in
software development– Not complete solution but starting point for design – Not code ready to use– Patterns have names and definitions– Built on common practices
Patterns should not be language dependant– However patterns apply for types of programming
languages
![Page 6: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/6.jpg)
History Patterns originated as an architectural
concept“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”
- Christopher Alexander
![Page 7: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/7.jpg)
History Landmark book from 1995:Design
Patterns: Elements of Reusable Object-Oriented Software– Gang of Four (GoF)– Term Design Pattern is
borrowed from theconstruction industry
Several books on patternshave been published since– Head First Design Patterns
for example
![Page 8: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/8.jpg)
Vintage Design Patterns Design Patterns are like good red wine
– You cannot appreciate them at first– As you study them you learn the
difference between plonk and vintage,or bad and good designs
– As you become a connoisseur you experience the various textures you didn’t notice before
Warning:– Once you are hooked, you will no longer be
satisfied with inferior designsDr. Heinz Kabutz (http://www.javaspecialists.co.za)
![Page 9: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/9.jpg)
Pattern Classification Design patterns can be classified based on
multiple criteria– Basic underlying problem they solve
Classification– Fundamental patterns – Creational patterns – Structural patterns – Behavioral patterns – Concurrency patterns
![Page 10: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/10.jpg)
Enterprise Patterns Classification Domain Logic Patterns Data Source Architectural Patterns Object-Relational Behavioral Patterns Object-Relational Structural Patterns Object-Relational Metadata Mapping Patterns Web Presentation Patterns Distribution Patterns Offline Concurrency Patterns Session State Patterns Base Patterns
![Page 11: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/11.jpg)
Which of these statements is not true
A) Design Patterns are based on solutions from practiceB) Design Patterns are ideas not codeC) Design Patterns are based on specific programming languagesD) Design Patterns can have ambiguous names
QUIZ
![Page 12: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/12.jpg)
Which of these statements is not true
A) Design Patterns are based on solutions from practiceB) Design Patterns are ideas not codeC) Design Patterns are based on specific programming languagesD) Design Patterns can have ambiguous names
QUIZ
✔
![Page 13: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/13.jpg)
Structure of Patterns
![Page 14: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/14.jpg)
Structure of Patterns Name The Intent The Sketch Motivation How it Works When to Use it Further Reading Examples
![Page 15: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/15.jpg)
The Name Pattern names are important
– Need to create a vocabulary– Need to describe the pattern well– Avoid ambiguity and misunderstanding
Problems with names– Authors are using different names for same
pattern • Data Access Object and Table Data Gateway• Dependency Injection and Inversion of Control
– Authors are using same name for different patterns
• Example: Value Object is used for two similar patterns
![Page 16: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/16.jpg)
The Intent Sums up the pattern in a sentence or two
– Value Object:
A small simple object, like money or date range, whose equality isn’t based on identity
![Page 17: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/17.jpg)
The Sketch Visual representation of the pattern, often
but not always a UML diagram
![Page 18: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/18.jpg)
Motivation Description of a motivating problem for
the pattern– Problem description– May not be the only problem for the pattern
Example: – Layered supertype
It’s not uncommon for all the objects in a layer to have methods you don’t want to have duplicated throughout the system. You can move this behavior into a common Layer Supertype
![Page 19: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/19.jpg)
How it Works Describes the solution
– Implementation Issues– Variations– Independent of any particular platform– Platform dependent sections are identified– UML Diagrams if applicable
Plugin example
![Page 20: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/20.jpg)
When to Use It Describes when the pattern should be
used– Trade-offs– Comparisons
Layered Supertype example– Use Layer Supertype when you have common
features from all objects in a layer
![Page 21: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/21.jpg)
Examples Example code in Java or C#
– Layer Supertype Not working code
– pseudo code to give idea
class DomainObject...
private Long ID; public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public DomainObject(Long ID) { this.ID = ID; }
![Page 22: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/22.jpg)
Using Design Patterns How to use design patterns?
– Problem is the patterns can be complex and detailed
– Usually they are generic and abstract Ways to study patterns
– Implement them in test code– Sketch a class diagram in your context to see
the class dependencies– Form a “Study group” to discuss the patterns– Learn the vocabulary– Practice, practice, practice
![Page 23: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/23.jpg)
Problems with Patterns Ambiguity in Vocabulary
– Same pattern has different names– Different Patterns have same name
Appling the wrong pattern– Over-designing the solution– Patterns design for one language might not be
needed in another Not solving the original problem
– Using Remote Façade instead of avoiding network latencies
– Using EJB Entity Beans
![Page 24: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/24.jpg)
Job interview question
You are given the assignment of creating a component that needs to know sales statistics of Lottery tickets. You know that there is a another component in the system, Sale Server, that handles the sale. You need real-time information. What would you suggest?
EXERCISE
![Page 25: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/25.jpg)
Sale server Bingo
First proposal: Sale Server will call Bingo
Problem is that the Sale Server developer refuses to make a call to a specific game. His argument is that Sale Server should be for sale, and not be cluttered with game specific code.
Another solution is needed.
![Page 26: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/26.jpg)
![Page 27: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/27.jpg)
Sale server Bingo
registerObserver
notify
![Page 28: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/28.jpg)
The Observer Pattern
![Page 29: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/29.jpg)
The Weather Monitoring Example The Weather Monitoring application
![Page 30: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/30.jpg)
The Weather Monitoring Example Task
– We need to implement measurementsChanged so that it updates three different displays for current conditions, weather stats, and forcasts
– measurementsChanged is called any time data changes, we don’t know or care how this method is called
– Three display types must be updated– The system must be expandable – new display
types will be added
![Page 31: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/31.jpg)
The Weather Monitoring Example WeatherData class
public class WeatherData{ // instance variable declarations
public void measurementsChanged() { float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure();
currentConditionsDisplay.update (temp, humidity, pressure); statisticsDisplay.update (temp, humidity, pressure); forcastConditionsDisplay.update (temp, humidity, pressure); } ...}
![Page 32: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/32.jpg)
Based on our first implementation, which of the following applyA. We are coding to concrete implementation not
abstractionsB. For every new display element we need to alter codeC. We have no way to add (or remove) display elements
at runtimeD. The display elements don’t implement a common
interfaceE. We have not encapsulated the part that changesF. We are violating encapsulation of the WeatherData
class
QUIZ
![Page 33: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/33.jpg)
The Weather Monitoring Example WeatherData class
public class WeatherData{ // instance variable declarations
public void measurementsChanged() { float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure();
currentConditionsDisplay.update (temp, humidity, pressure); statisticsDisplay.update (temp, humidity, pressure); forcastConditionsDisplay.update (temp, humidity, pressure); } ...}
By coding to concreate implementation we have no way to add or remove displays without code change
Interface is that same for all
![Page 34: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/34.jpg)
ObserverOne or more observers or listeners are registered
to observe an event which may be raised by the observed object (the subject)
Sometimes called publish/subscribe– Similar to call-back handlers– One-to-Many relationship
Benefits– Listening object gets information when needed– Subject does not become dependent on multiple
observers
![Page 35: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/35.jpg)
Observer Design Pattern
![Page 36: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/36.jpg)
Observer Design Pattern Subject does not depend on listeners
![Page 37: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/37.jpg)
Loose Coupling When two object are loosley coupled, the can
interact but they have very little knowledge of each other
The Observer Pattern loosley coupled design– The only thing the subject knows about observer is
that it implements a ceratain interface– We can add new observers at any time– We never need to modify the subject to add new types
of observers– We can reuse subjects or observers independent of
each other
![Page 38: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/38.jpg)
Loosley Coupled Principle
Strive for loosely coupled designs between objects that interact
![Page 39: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/39.jpg)
Weather Station Examplepublic interface Subject{ public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObservers();}
public interface DisplayElement{ public void display();}
public interface Observer{ public void update(float temp, float humidity, float pressure);}
![Page 40: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/40.jpg)
Weather Station Examplepublic class WeatherData implements Subject{ private ArrayList observers; private float temperature, humidity, pressure; public WeatherData() { observers = new ArrayList(); } public void registerObserver(Observer o) { observers.add(o); } public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i>= 0) observers.remove(i); }
POLYMORPISHM
![Page 41: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/41.jpg)
Weather Station Example public void notifyObservers() { for (int i = 0; i<observers.size(); i++) { Observer observer = (Observer)observers.get(i); observer.update(temperature, humidity, pressure); } } public void measurementsChanged() { notifyObservers(); } // Test code public void setMeasurement(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; this.measurementsChanged(); }
POLYMORPISHM
![Page 42: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/42.jpg)
Weather Station Examplepublic class CurrentConditionsDisplay implements Observer, DisplayElement{ private float temperature, humidity; private Subject weatherData; public CurrentConditionsDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float temp, float humidity, float pressure) { this.temperature = temp; this.humidity = humidity; display(); } public void display() { System.out.println("Current conditions: " + temperature + "C " + "Humidity: " + humidity + "%"); }}
Registeringthis as an observer
The subject will call update
![Page 43: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/43.jpg)
Weather Station Examplepublic class WeatherStation{ public static void main(String[] args) { WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurement(15, 50, 30); }}
Current conditions: 15.0C Humidity: 50.0%
![Page 44: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/44.jpg)
Loose Coupling When two object are loosley coupled, the can
interact but they have very little knowledge of each other
The Observer Pattern loosley coupled design– The only thing the subject knows about observer is
that it implements a ceratain interface– We can add new observers at any time– We never need to modify the subject to add new types
of observers– We can reuse subjects or observers independent of
each other
![Page 45: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/45.jpg)
Loosley Coupled Principle
Strive for loosely coupled designs between objects that interact
![Page 46: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/46.jpg)
The Open-Closed Principle
![Page 47: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/47.jpg)
The Open-Closed Principle
Software entities like classes, modules and functions should be open for extension but closed for modifications
![Page 48: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/48.jpg)
The Open-Closed Principle Design and write code in a fashion that
adding new functionality would involve minimal changes to existing code– Most changes will be handled as new methods
and new classes– Designs following this principle would result in
resilient code which does not break on addition of new functionality
![Page 49: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/49.jpg)
public class ResourceAllocator{ ... public int allocate(intresourceType) { intresourceId; switch (resourceType) { case TIME_SLOT: resourceId = findFreeTimeSlot(); markTimeslotBusy(resourceId); break; case SPACE_SLOT: resourceId = findFreeSpaceSlot(); markSpaceSlotBusy(resourceId); break; ... } return resourceId; }...
Resource Allocator Example
Holy Buckets!!I need to change the class for new types!!! Horrible!
![Page 50: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/50.jpg)
Resource Allocator Example Design for extensions
List resources = new ArrayList();...public int allocate(intresourceType){ int resourceId = findFreeResource(resourceType); markAsBusy(resourceId); return resourceId;}
![Page 51: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/51.jpg)
Another Exampleprotected String normalize(char cCharacter) { switch(cCharacter) { case '<': return "<"; case '>': return ">"; case '&’: return "&"; case '"’: return """; default: return ""+cCharacter;} }
This is not complete This is common problem – a library must
exists If making it yourself, a Map would be
better
What is wrong withthis code?
![Page 52: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/52.jpg)
Callback Handlers
![Page 53: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/53.jpg)
TaskWe need to create program that reads feedsFeed can be RSS news, XML or what ever
The program must be loosely coupledNew feed types will come
![Page 54: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/54.jpg)
Creating Objects Where does the creation take place?
Enterprise Application
This stays the sameThis that is added
![Page 55: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/55.jpg)
Call-back Handlers Inverting the Dependency
– Let a class call you back
Example– sort routine, reading records
ReaderProcess RssFeedReader
processEntryprocessEntryprocessEntry
Read
![Page 56: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/56.jpg)
Example: Reading RSS Process to read an RSS feed
– The FeedReader define the role of such readers
– Concrete readers must implement read and accept a call-back handler to get the results back
public interface FeedReader{ public boolean read(); public void setFeedHandler(FeedHandler handler);}
public interface FeedHandler{ public void processEntry(FeedEntry entry);}
![Page 57: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/57.jpg)
Example: Reading RSS AbstractFeedReader acts as a
superclass for concrete reader classes – Layered Supertype pattern
public abstract class AbstractFeedReader implements FeedReader{ protected FeedHandler feedHandler; public void setFeedHandler(FeedHandler handler) { this.feedHandler = handler; } public abstract boolean read();}
![Page 58: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/58.jpg)
Example: Reading RSS RssFeedReaderpublic class RssFeedReader extends AbstractFeedReader{ private String source;
public RssFeedReader(String source) { this.source = source; }
public boolean read() { // reading ... feedHandler.processEntry(new FeedEntry(ent.getTitle(), ent.getLink(), ent.getPublishedDate().toString())); } return true; }}
![Page 59: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/59.jpg)
Example: Reading RSS ReaderProcess is the clientpublic class ReaderProcess implements FeedHandler{ FeedReader reader;
public ReaderProcess() { ReaderFactory factory = ReaderFactory.getReaderFactory(); reader = factory.getFeedReader("http://..."); reader.setFeedHandler(this); }
public void processEntry(FeedEntry entry) { ... }}
![Page 60: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/60.jpg)
Example: Reading RSS
![Page 61: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/61.jpg)
Call-back Handlers Inverting the Dependency
– Let a class call you back
Example– sort routine, reading records
ReaderProcess RssFeedReader
processEntryprocessEntryprocessEntry
Read
![Page 62: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/62.jpg)
Factory
![Page 63: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/63.jpg)
The Problem with “new” new is used to create object Problem is this:
– Even if we use supertypes (interfaces or abstract classes) we have to have concrete class behind it
– This violates the Program to Interfaces Design Principle
– The code also violates the Open Closed Principle
Animal animal = new Dog();animal.makeSound();
![Page 64: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/64.jpg)
Program to an interfacesDependency Injection– Make the caller responsible for setting the
dependencyprivate Animal animal;
public setAnimal(Animal animal){ this.animal = animal;}...
animal.makeSound();
Injection happens here, in the set-method
LOOSE COUPLING = BEAUTIFUL!
![Page 65: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/65.jpg)
Program to unknown creation What does this mean?
Animal animal = getAnimal();animal.makeSound();
Where is this getAnimal
coming from?
![Page 66: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/66.jpg)
FeedReader Objects are created with new
public class ReaderProcess { FeedReader reader;
public ReaderProcess() { reader = new RssFeedReader ("http://www.mbl.is/mm/rss/togt.xml");}
Holy Cow! new creates concrete object not abstraction!!
![Page 67: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/67.jpg)
FeedReader We need to have diffrent types
public ReaderProcess(String type, String source){ if(type.equals("rss")) reader = new RssFeedReader(source); else if (type.equals("atom")) reader = new AtomFeedReader(source); else if (type.equals("xml")) reader = new XmlFeedReader(source); reader.setFeedHandler(this);}
Holy Macaroni!This smells!!!Violates the OCP
![Page 68: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/68.jpg)
Moving the Dependency The name of the class is put in to a
properties file– ReaderFactory has no clue of what class it is– It just has to be a subclass of FeedReader public static FeedReader getFeedReader()
{ FeedProperties prop = new FeedProperties(); Class instanceClass; FeedReader reader = null; try { instanceClass = Class.forName(prop.getProperty("reader")); reader = (FeedReader)instanceClass.newInstance(); } catch (Exception e) { System.out.println("loading class failed"); return null; } reader.setSource(prop.getSource()); return reader; }
Plugin pattern
![Page 69: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/69.jpg)
Loading Properties Properties class
public class FeedProperties extends Properties{ protected String reader; protected String source; protected String DEFAULT_PROPERTIES = "feeds.properties";
public FeedProperties() { try { load(new FileInputStream(new File(DEFAULT_PROPERTIES))); reader = getProperty("reader"); source = getProperty("source"); } catch (Exception e) { System.out.println("Loading properties failed"); } }
feeds.propertiesreader=is.ru.honn.feeds.rss.RssFeedReadersource=http://www.mbl.is/mm/rss/togt.xml
![Page 70: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/70.jpg)
Base Patterns
![Page 71: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/71.jpg)
Base Patterns Gateway Mapper Layer Supertype Separated Interface Registry Value Object Plugin Service Stub
![Page 72: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/72.jpg)
Fowler’s Cataloghttp://martinfowler.com/
eaaCatalog/
![Page 73: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/73.jpg)
Gateway (466)An object that encapsulates access to an
external system or resource Wrap external APIs into an interface
– API is usually for accessing some external resource• Examples: JDBC, JDom, financial software
![Page 74: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/74.jpg)
Gateway (466) How It Works
– Create a simple API and use it access the external API through a Gateway
– All access is easily defined– Change in the resource does not require
changes in the client software– Gateways should be simple – complex logic
should not be in the clients of the Gateway– Gateways can be generated
![Page 75: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/75.jpg)
Gateway (466) When to Use It
– Gateway is useful when accessing external service
– Can be applied with Service Stub (504)– Clear benefit is that is makes it easy to swap
out one kind of resource for another
![Page 76: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/76.jpg)
Mapper (473)An object that sets up communiction
between two independent objects Create communication between two
systems but you still need to make them independent
![Page 77: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/77.jpg)
Mapper (473) How it Works
– A Mapper is an insulating layer between subsystems– It controls the details of communication between
them without either subsystem being aware of it– Mappers are fairly easy as they are well-defined– The tricky part is what system invokes them – third
party system or make the Mapper an Observer When to Use it
– When you want to decouple different parts of a system
![Page 78: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/78.jpg)
Layer Supertype (475)A type that acts as the supertype
for all types in its layer Super class that contains common
functionality in a layer How it works
– Use this pattern when you have common features from all objects in a layer
![Page 79: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/79.jpg)
Layer Supertype (475) When to use it
– When you have common features from all objects in a layer.
Example– Domain objects can
have a common superclass for ID handling
class DomainObject...
private Long ID; public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public DomainObject(Long ID) { this.ID = ID; }
![Page 80: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/80.jpg)
Example: Drawing system Shape class revisited
– All objects in the drawing layer must have an origin (x and y) and implement Drawable
public abstract class Shape implements Drawable{ protected int x,y;}
![Page 81: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/81.jpg)
Separated Interface (476)Defines an interface in a separate package from its implementation
Decouples parts of a system– Controls the dependencies between packages– Implementation can easily be changed
How it works– Interface and implementation is placed in
separate packages– Client uses the interface– Implementation can be determined at
configuration time
![Page 82: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/82.jpg)
Separated Interface Layered System
– Domain layer depends on Data Source layer– Data Source layer cannot access Domain layer
Data Source Layer
Domain Layer
JDBCCode
InterfaceRowCallBackHandler
processRow(ResultSet rs)
Concreate classRowCallBackHandler
processRow(ResultSet rs)
implements
Code reading SQL
Execution calls
Separated interface
![Page 83: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/83.jpg)
Separated Interface (476) Implementation is placed in a separate
packageDevelopers of the client package are responsible for the interface
![Page 84: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/84.jpg)
Separated Interface (476)
![Page 85: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/85.jpg)
Separated Interface (476) Instantiating the implementation
– User of the interface should not know the implementation
Solutions– Use a Factory and Plugin method– Use Dependency Injection
![Page 86: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/86.jpg)
Separated Interface (476)public interface FeedHandler{ public void processObject (FeedEntry entry);}
public class ReaderClient implements FeedHandler{ ... public ReaderClient() { FeedReader reader = ReaderFactory.getFeedReader(); reader.setFeedHandler(this); reader.read("http://rss.news.yahoo.com/rss/tech"); }
public void processObject(FeedEntry entry) { System.out.println(entry); }}
Callback
![Page 87: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/87.jpg)
Registry (480)A well-known object that other objects can use to find common objects and services
A registry is a global object How It Works
– Object that can easily be accessed at any time– Only one object available at any time– Provides services or information– Can have different scopes– Usually not mutable data– Example: System Settings, Loggers
![Page 88: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/88.jpg)
Singleton Registry (480) Only one instance running
When to Use It– As a last resort
public class Registry{ private static Registry soleInstance = new Registry();
public static Registry getInstance() { return soleInstance; }
private Registry() { } ...}
Registry registry = Registry.getInstance();//registry = new Registry (); Does not work
![Page 89: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/89.jpg)
Value Object (486)A small simple object, like money or date
range, whose equality isn’t based on identity
Small and easily created objects that hold and represent some data
How it works– Not based on identity– Equality is based on comparing values of the object– Can be immutable (example is the Date class)
When to use it– When you’re basing equality on something other than
identify
![Page 90: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/90.jpg)
Value Object (486) Examples
– Date, Money
class Money...
private long amount; private Currency currency;
public Money(double amount, Currency currency) { this.currency = currency; this.amount = Math.round(amount * centFactor()); } ...
![Page 91: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/91.jpg)
Value Object Example: DateGregorianCalendar cal = new GregorianCalendar();
cal.set(1865, Calendar.APRIL, 14);Date d1 = cal.getTime();cal.set(1963, Calendar.NOVEMBER, 22);Date d2 = cal.getTime();
System.out.println(d1.equals(d2));
cal.set(1756, Calendar.JANUARY, 27);Date d3 = cal.getTime();Date d4 = cal.getTime();
System.out.println(d3.equals(d4));falsetrue
![Page 92: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/92.jpg)
Plugin (499)Links classes during configuration
rather than compilation Use plugin to provide specific implantation
– Plugins implement specific interface use by the client application code
– Decision at configuration time or run time– Use factory to load in the plugin– For example: on plugin for test, another for
production
![Page 93: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/93.jpg)
Plugin (499)
caller a plugin factory a plugin configuration
getPlugin
lookupPluginByType
newa plugin
A caller obtains a Plugin implementation of a separated interface
When to Use It– Use plugin when you have behavior that
requires different implementations based on runtime environment
![Page 94: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/94.jpg)
Plugin (499) ReaderClient uses ReaderFactory to get an
interface to FeedReader
reader.properties define the name of the actual implementation class
ReaderClient ReaderFactory reader.properties
getFeedReader
props.getProperty("reader")
newFeedReader
![Page 95: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/95.jpg)
Plugin (499)public ReaderClient(){ FeedReader reader = ReaderFactory.getFeedReader(); ...} public class ReaderFactory
{ public static FeedReader getFeedReader() { ... try { props.load(new FileInputStream(new File("reader.properties"))); instanceClass = Class.forName(props.getProperty("reader")); reader = (FeedReader)instanceClass.newInstance(); } ... return reader; }} reader=RssFeedReader
![Page 96: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/96.jpg)
Service Stub (504)Removes dependence upon problematic
services during testing Enterprise systems often need to access
external system– Can be out of developers control
![Page 97: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/97.jpg)
Service Stub (504) Service stub provides implementation for
development and testing purposes– Runs locally and in-memory– Implements the same interface of the gateway
used to access the real service When to Use It
– Service stub is useful when dependence on a particular service is hindering development or testing
– Called “Mock Object” in the extreme programming world
![Page 98: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/98.jpg)
Service Stub Examplespublic class ReaderStub extends AbstractFeedReader{ public void read(String url) { feedHandler.processEntry(new FeedEntry("title1", "Bla bla bla")); feedHandler.processEntry(new FeedEntry("title2", "Bla bla bla")); feedHandler.processEntry(new FeedEntry("title3", "Bla bla bla")); }}
title1Bla bla blatitle2Bla bla blatitle3Bla bla bla
reader=ReaderStub
reader.properties
![Page 99: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/99.jpg)
Summary Base Patterns
– Gateway, Mapper, Layerd Supertype, Separated Interface, Registry, Value Object, Plugin, Service Stub, Record Set
Next: From Problem to Patterns– Using design patterns
![Page 100: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/100.jpg)
QUIZ
![Page 101: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/101.jpg)
Question #1 You use this patterns when you need to
break a dependency between two parts of the system
A) RegistryB) GatewayC) Separated InterfaceD) Plugin
![Page 102: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/102.jpg)
Question #2 Intent of a pattern is this: An object
that sets up communication between two objects
A) GatewayB) MapperC) RegistryD) Value Object
![Page 103: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/103.jpg)
Question #3 Sketch of a pattern is his
A) PluginB) MapperC) RegistryD) Service Stub
![Page 104: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/104.jpg)
Question #4 Use this pattern when you find that
dependence on a particular service is hindering your development and testing
A) MapperB) Record SetC) Service StubD) Gateway
![Page 105: L05 Design Patterns](https://reader033.vdocument.in/reader033/viewer/2022061217/54b480c14a795971678b459b/html5/thumbnails/105.jpg)
Next Using Design Patterns