Kĩ thuật lập trình - Design patterns

Design patterns aim to provide ideas and recipes for sound OO software design. The origin of the idea can be traced to some influential books on architecture by Christopher Alexander (for example, The Timeless Way of Building, 1979). Hundreds of OO design patterns have been published since 1995 in books, web sites, etc.

ppt31 trang | Chia sẻ: huyhoang44 | Lượt xem: 612 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Design patterns, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Design PatternsCopyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.Java MethodsObject-Oriented Programmingand Data StructuresMaria Litvin ● Gary Litvin2nd AP edition  with GridWorld1Objectives:Explore the concept of design patternGet familiar with six introductory design patterns:FaçadeStrategySingletonDecoratorCompositeMVC (Model-View-Controller)2Design PatternsDesign patterns aim to provide ideas and recipes for sound OO software design.The origin of the idea can be traced to some influential books on architecture by Christopher Alexander (for example, The Timeless Way of Building, 1979).Hundreds of OO design patterns have been published since 1995 in books, web sites, etc.3Design Patterns (cont’d)A typical description of a design pattern includes:namebrief statement of purposedescriptionthe types of classes and objects involvedstructural diagramexample(s)4Façade Design PatternServes to facilitate the use of a complicated subsystem or package of classesReplaces multiple complex interfaces to several classes with one simplified interface to the whole subsystemEasySound5Façade (cont’d)Can be used to encapsulate a process that involves several steps. For example: ... Rectangle ocrArea = new Rectangle(200, 20, 120, 30); ImageEditor imageEditor = new ImageEditor(); image = imageEditor.cut(image, ocrArea); TextLocator locator = new TextLocator(); ocrArea = locator.findTextField(image); String charSet = "0123456789"; OCRReader reader = new OCRReader(charSet); String result = reader.ocr(image, ocrArea); ... String result = OCR.read(image, ocrArea);6Strategy Design PatternIf an object (“Player”) may use different strategies to accomplish a task, make the strategy module pluggable:Pass a “Strategy” object to Player’s constructor or method as a parameter.The Strategy object “knows” how to accomplish the task in a particular way.The Strategy object may also “know” how to adjust the strategy if necessary or pass a strategy object of a different type to Player.7Strategy (cont’d)public interface Strategy{ void doSomething (...);}public class StrategyOne implements Strategy{ public void doSomething(...) {...}}public class StrategyTwo implements Strategy{ public void doSomething (...) { }}public class Player{ private Strategy myStrategy; public Player (... , Strategy s) { ... myStrategy = s; } public void setStrategy (Strategy s) { myStrategy = s; } public void performTask (...) { myStrategy.doSomething (...); } ...}8Singleton Design PatternIs used when the same object must be accessible in several classes.A separate class holds a static variable that refers to the singleton.A static accessor method is provided for the singleton.The singleton is initialized only on the first call to the accessor.9public class SchoolLogo{ private static ImageIcon logo = null; public static ImageIcon get ( ) { if (logo == null) logo = new ImageIcon ("eagles.jpg"); return logo; }Singleton — Example 1public class School{ public static void main (String [ ] args) { ImageIcon logo = SchoolLogo.get ( ); }}10public class RandNumGenerator{ private static Random theRandNumGenerator = new Random( ); public static Random getInstance ( ) { return theRandNumGenerator; }}Singleton — Example 2public class Fish{ ... Random gen = RandNumGenerator.getInstance ( ); ...}11Decorator Design PatternSolves two problems:Helps add the same functionality to classes on diverging inheritance pathsLetterCertifiedRegisteredLtrWithRetReceiptLtrWithRetReceiptHelps add or modify functionality of an object at run time Circle cir = new Circle (x0, y0, radius); cir.draw (); cir.move (x, y); DottedLineCircle cirDL = new DottedLineCircle (cir); cirDL.draw ();12Decorator (cont’d)The Decorator class (a.k.a. wrapper class) extends the decorated class.A Decorator (wrapper) object also embeds the decorated (wrapped) object.LetterLtrWithRetReceipt13Decorator (cont’d)Decorator class’s constructor takes a wrapped object as a parameter:public class LtrWithRetReceipt extends Letter{ private Letter myLetter; public LtrWithRetReceipt (Letter ltr) { myLetter = ltr; } ...}14Decorator (cont’d)The decorator object passes method calls to the “decoratee”; can modify some of the methods:public class LtrWithRetReceipt extends Letter{ private Letter myLetter; private static final double retReceiptFee = 2.25; ... public double getWeight ( ) { return myLetter.getWeight ( ) ; } public double getCost ( ) { return myLetter.getCost ( ) + retReceiptFee; } ...}15Decorator (cont’d)Decorator design is a kind of do-it-yourself run-time inheritance.public class PostageCalculator{ public static void main (String [ ] args) { ... Letter ltr1 = new Letter (weight, destZip); Letter ltr2 = new LtrWithRetReceipt (ltr1); System.out.println ( " Cost: " + ltr1.getCost () + " With return receipt: " + ltr2.getCost ()); }}16Decorator (cont’d)The java.io package relies extensively on the Decorator design pattern: ... myInputFile = new BufferedReader (new FileReader (fileName), bufferSize);17Composite Design PatternIs used to represent recursive (nested) structuresApplies when a list or a set of objects of a certain type is also an object of that typeExample 1: Text is a composite for Message objects; a Text object is also a Message.Example 2: A LinkedList is a composite for Objects because a LinkedList is an Object.18Composite (cont’d)The composite class extends the “simple” class.A Composite object also embeds a list or a set of “simple” or composite objects.MessageTextpublic class Text extends Message{ private List messages; // Holds Message or Text objects public void add (Message m) { messages.add(m); } ... public void toString ( ) { return messages.toString ( ); }}Relies on polymorphism 19Composite (cont’d)Another version: both “simple” and “composite” classes implement the same interface«Interface» DrawableDrawingSimpleStroke20Composite (cont’d)pic can be a SimpleStroke or a Drawing public interface Drawable{ void draw (Graphics g);}public class SimpleStroke implements Drawable{ ... public void draw (Graphics g) { g.drawLine (x1, y1, x2, y2); }}public class Drawing implements Drawable{ private Drawable [ ] pics; ... public void draw (Graphics g) { for (Drawable pic : pics) pic.draw (g); }}21Model-View-Controller (MVC) Design PatternIs used to support different concurrent or optional views of a changing “model.”The model is an object that represents a system, a situation, a mathematical object.The views are automatically updated when the model changes.It is easy to attach different views to the same model.22MVC (cont’d)“Totalitarian” designMVC designWhen the model’s state changes, the model updates all the views attached to it23MVC (cont’d)The model class extends java.util.Observable, which provides addObserver, setChanged, and notifyObservers methods:public class Sphere extends java.util.Observable{ ... public void setRadius (double r) { myRadius = r; setChanged ( ); notifyObservers ( ); } ...}24MVC (cont’d)A view class implements java.util.Observer by providing an update method:public class TextView implements java.util.Observer{ ... public void update (Observable model, Object arg) { Sphere s = (Sphere) model; ... ... public class GraphicsView implements java.util.Observer{ ... public void update (Observable model, Object arg) { Sphere s = (Sphere) model; double r = s.getRadius ( ); ... }}25MVC (cont’d)main (or another constructor or method) can attach one or more views to the model:public class MVCSphereDemo{ public static void main (String [ ] args) { Sphere sphere = new Sphere (100); sphere.addObserver (new TextView ( )); sphere.addObserver (new GraphicsView ( )); ... } ...}26OO design patterns and tools represent a bold attempt to turn the art of software design into something more precise, scientific, and teachable. But, behind all the technical terms and fancy diagrams, some art remains an essential ingredient.Science or Art?27Something — not only the need to finish a project on time — compels a designer to look for what Christopher Alexander called “the quality without a name”: order, balance, economy, fit to the purpose, and, in Alexander’s words, “a subtle kind of freedom from inner contradictions.” Quality without a name...28Review:What is the purpose of design patterns?Describe briefly the Façade design pattern.When do we use Singleton?Come up with an example where the Strategy design pattern is called for.Name a library package where Strategy is used.29Review (cont’d):Describe briefly the Decorator design pattern.Name a library package where Decorator is used.What is the purpose of the Composite design pattern?Come up with an example where the Composite design pattern is appropriate.30Review (cont’d):What is the main idea of the Model-View-Controller design pattern?Name the Java library tools (classes, interfaces, methods) that support MVC.31

Các file đính kèm theo tài liệu này:

  • pptch27_4354.ppt