Introduction to design patterns

  • View
    697

  • Download
    1

Embed Size (px)

DESCRIPTION

Org title: design patterns for desktop application development.This presentation take a very brief tour at GoF commonly used design patterns and discuss theirs principles, benefits and uses.

Text of Introduction to design patterns

Design Patterns

Design Patterns Desktop Application DevelopmentHanoi - February, 2010Duong Trong Tan, (tandt@fpt.edu.vn)forOr : An simple introduction to design patterns1ContentsDesign IssuesDesign principlesWhat is design pattern?Patterns classificationCommonly used patternsCase studies2NoticeThis discussion involves lots of questions, not answerI assume that you are good at core Java conceptsand these following symbols:A3What if you dont satisfy the condition?3Design Issues Design principles What is design pattern? Patterns classification Commonly used patterns Case studies4Ill come up with some brain storming questions. I wont answer these questions4What is design?5

Design: analyze and solve the problem

5What is a good Design?6

For current vs. future, small vs. big program, multi-versions sw vs. code and throw away6A constant: CHANGE!7COUPLING | COHESION8Question marks8Design Principles Design issues

What is design pattern? Patterns classification Commonly used patterns Case studies9Design PrinciplesEncapsulate what variesFavor composition over inheritanceProgramming to interfaces not to implementationsStrive for loosely coupled between objects that interactClasses should OPEN for extension and CLOSE for modificationDepends on abstraction, not concrete classes Don't call us, we'll call youA class should have only one reason to change

Freeman et al., 2004

10What is design pattern? Design issues Design principles

Patterns classification Commonly used patterns Case studies11WHAT ARE TEMPLATES?12

Think: Document templates, cv, plan, websites, etc.12What is a design pattern?A design pattern is a general reusable solution to recurring problemPatterns can specify how objects are created, how they interact, or how they are structuredtypically deal with a small number of classes, but can be of any size

1313Why patterns?Provide a communication framework in which ideas can be discussed at a high levelUnderstand current systems or APIs betterGuide you quickly find solutionsBetter design: flexible, maintainableBuild sustainable products14Ask: what are the most difficult thing when you develop sw as a team?14Brief history of design patternsIdea of pattern in civil architecture was originated by Alexandre Christopher1995: GoF published: Design Patterns: Elements of Object-Oriented SoftwareNow: Design patterns are language-independentJava, C#, VB, Ruby, PHP, Smalltalk, etc.15

Image courtesy to www.selectorweb.comCover img of GoFs book15Patterns classification Design issues Design principles What is design pattern?

Commonly used patterns Case studies16Open and Discuss the GoFs classification.Application Type Compatible: Biz, Desk, Mobile, Enterprise1617Creational patterns: how objects are created (Singleton, Builder, etc.)Structural patterns: how they are structured (Faade, Composite, Adapter, etc.)Behavioral patterns: how they interact, (Strategy, Iterator, etc.)

17Commonly used Patterns Design issues Design principles What is design pattern?Patterns classification

Case studies18ScenarioCounter19How to counting number of users in a chat room, game session, clients connected Think about the similar situations

19SingletonMakes sure only one instance of an object exists within an application. A better solution compared to global variables Provide global access to the object instance.Example: Counter, Application Menu System, Application objects, Services, Clients20

View the example

Issues: What about threading? (in concurrent programming, server-side programming)

20ScenarioEnter the complex world through an entry21Faade

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.(GoF)

22The DBFacade ExampleCommon JDBC uses:Open a connection to DBClose a connectionGet all tables from DBExecutes a SQL statementRetrieve result from a SELECT statement

It looks simpler 23DatabaseFacade OutlookJDBC APIDatabaseFacadeClientusesConnectionStatementResultSetDatabaseMetadataResultSetMetadataDriver24ScenarioSorting Employees2525Strategy

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it26ScenarioWhat does this code snippet do?int totalSold = 0;List sales = new LinkedList();sales = dataSource.getAllData();

for( Employee staff : sales){totalSold += staff.getProductsSold();}//see above initIterator itr = sales.iterator();while( itr.hasNext())totalSold += itr.next().getProductsSold();}27View the code in NetBeans, run it.

How can you traverse through the linked list? (see verbose code)27What do you call this data structure?

28Brain storming: find the situation that you think data should be store in this kind of structure.How can you visit each item

28Can we do this?int totalSold = 0;Tree sales = new BinaryTree();sales = dataSource.getAllData();

for( Employee staff : sales){totalSold += staff.getProductsSold();}29Iterator30

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.ScenarioReflecting latest data 31

View the ModelSharing demo:JTextArea text1 = new JTextArea("starting text", 5, 30); JTextArea text2 = new JTextArea(5, 30); text2.setDocument(text1.getDocument());

Container pane = getContentPane(); pane.add(new JScrollPane(text1)); pane.add(new JScrollPane(text2));31Observer

GoFDefine a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.32MVC33

Robert Eckstein, Sun

This tech article is really cool: http://blogs.sun.com/JavaFundamentals/entry/java_se_application_design_with 33Demo: Observer and MVC in Swing34

34Command

Lets hide (encapsulate) the way we call (invoke) methods.35Example: MenusConsider an application menu system.How do we de-couple our menu system from our document class?

Command InterfaceClientWe can do a lot of things (actions) with a document. Each interface might be different!ReceiverConcreteCommandMenu contains many menu items.Composite Pattern!invoker36GoF patterns

37These are classical patterns only, the number of dps are increasing. For your toolbox, learn day-by-day and get design patterns benefits.37Case Studies Design issues Design principles What is design pattern?Patterns classification Commonly used patterns

38Where are cases studies?Consider the previous scenarios and answer.38ReferencesFreeman,E. , Freeman,E. , Bates, B. & Siera, K., Head First Design Patterns, O'Reilly Media, 2004.Erich Gamma , Richard Helm , Ralph Johnson , John Vlissides, Design Patterns: Elements of Object-Oriented Software. Addison-Wesley, Boston, 1995.Robert Eckstein, Java SE Application Design With MVC, Sun (http://blogs.sun.com/JavaFundamentals/entry/java_se_application_design_with )39Resourceshttp://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdfhttp://www.artima.com/lejava/articles/designprinciples.htmlhttp://www.oodesign.com/http://www.javaworld.com/channel_content/jw-patterns-index.html

40