Object-Oriented Design and Programming (Java). 2 Topics Covered Today 2.3 Advanced Class Design –2.3.4 Design Patterns –2.3.5 Singleton Pattern –2.3.6.

Slides:



Advertisements
Similar presentations
Winter 2007ACS-3913 Ron McFadyen1 Duck Example Consider the text example (up to page 6). Each type of duck is a subclass of Duck Most subclasses implement.
Advertisements

+ Informatics 122 Software Design II Lecture 7 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
D ESIGN P ATTERNS Introduction. C OURSE D ESCRIPTION Traditionally, OO designers have developed their own private "catalogs" of solutions to recurring.
Informatics 122 Software Design II
Strategy Pattern1 Design Patterns 1.Strategy Pattern How to design for flexibility?
Plab – Tirgul 12 Design Patterns
Patterns Reusable solutions to common object-oriented programming problems When given a programming problem, re-use an existing solution. Gang of Four.
Informatics 122 Software Design II Lecture 5 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
05/26/2004www.indyjug.net1 Indy Java User’s Group June Knowledge Services, Inc.
(c) 2009 University of California, Irvine – André van der Hoek1June 13, 2015 – 21:42:16 Informatics 122 Software Design II Lecture 8 André van der Hoek.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
Design Patterns William A. Hoffman NYU OOP Class.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Design Patterns: someone has already.
Spring 2010ACS-3913 Ron McFadyen1 Duck Example Consider the text example (up to page 6). Each type of duck is a subclass of Duck Most subclasses implement.
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
CERN – European Organization for Nuclear Research GS Department – Administrative Information Services Design Patterns in Groovy Nicolas Décrevel Advanced.
Design Patterns Alan Shalloway, James Trott, Design Patterns Explained, Addison-Wesley, Gamma, Helm, Johnson, Vlissides, Design Patterns, Elements.
Chapter 1: Introduction to Design Patterns. SimUDuck Example.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
1 Unit 5 Design Patterns: Design by Abstraction. 2 What Are Design Patterns?  Design patterns are: Schematic descriptions of design solutions to recurring.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
January 12, Introduction to Design Patterns Tim Burke References: –Gamma, Erich, et. al. (AKA, The Gang of Four). Design Patterns: Elements of Reusable.
Design Patterns in Java Chapter 1 Introduction Summary prepared by Kirk Scott 1.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
CS 325: Software Engineering February 12, 2015 Applying Responsibility-Assignment Patterns Design Patterns Situation-Specific Patterns Responsibility-Assignment.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
CSE 403, Spring 2008, Alverson Software Design “There are two ways of constructing a software design: one way is to make it so simple that there are obviously.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Introduction to Design Patterns. Questions What is a design pattern? Who needs design patterns? How different are classes and objects in APL compared.
05/26/2004www.indyjug.net1 Indy Java User’s Group May Knowledge Services, Inc.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Design Patterns. 1 Paradigm4 Concepts 9 Principles23 Patterns.
Design Patterns Introduction
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
CS251 – Software Engineering Lectures 18: Intro to DP Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others 1 و ابتغ فيما آتاك الله الدار.
CS 210 Introduction to Design Patterns August 29, 2006.
CS 210 Review October 3, 2006.
It started with a simple … A highly successful duck pond simulation game called SimUDuck The game can show a large variety of duck swimming and making.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
SE 461 Software Patterns Welcome to Design Patterns.
Intro to Design Pattern
Design Patterns: MORE Examples
Strategy Pattern.
The Object-Oriented Thought Process Chapter 15
Chapter 10 Design Patterns.
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
object oriented Principles of software design
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2005 Instructor: Patrice Chalin.
Strategy Design Pattern
Software Engineering Lecture 7 - Design Patterns
Informatics 122 Software Design II
Object-Oriented Programming
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2005 Instructor: Patrice Chalin.
DESIGN PATTERNS : Introduction
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2004 Instructor: Patrice Chalin.
Informatics 122 Software Design II
Software Design Lecture : 27.
Presentation transcript:

Object-Oriented Design and Programming (Java)

2 Topics Covered Today 2.3 Advanced Class Design –2.3.4 Design Patterns –2.3.5 Singleton Pattern –2.3.6 Strategy Pattern

3 Reference > –ISBN – > 机械工 业出版社 > – > ISBN:

4 History Patterns originated as an architectural concept by Christopher Alexander. The Timeless Way of Building – 《建筑的永恒之道》

5 Alexander’s Pattern

6 Alexander’s Pattern.

7 Alexander’s Pattern.. Patterns describe a solution so that it can be applied many times without ever being the same.

8 History In 1980s, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming.

9 History Design patterns gained popularity in computer science after the book > by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Gang of Four or GoF) was published in 1994.

10 Design Pattern Design patterns describe practical solutions to common design problems that occur repeatedly in software development. A design pattern description consists of: –Pattern name –A description of the problem that the pattern addresses –A description of the solution (for instance: class structure) –A discussion of the consequences of using the pattern

11 Classification Creational Patterns ( 创建模式 ) –deal with object creation mechanisms Structural Patterns ( 结构模式 ) –describe how classes and objects can be combined to form larger structures. Behavioral Patterns ( 行为模式 ) –identify common communication patterns between objects and realize these patterns.

12 23 Design Patterns Creational Patterns ( 创建模式 ) Abstract Factory ( 抽象工厂 ) Prototype ( 原始模型 ) Singleton ( 单例 ) Builder ( 构建器 ) Factory Method ( 工厂方法 ) Structural Patterns ( 结构模式 ) Adapter ( 适配器 ) Bridge ( 桥梁 ) Composite ( 合成 ) Decorator ( 装饰 ) Fa ç ade ( 外观 ) Flyweight ( 享元 ) Proxy ( 代理 ) Behavioral Patterns ( 行为模式 ) Chain of Responsibility ( 责任链 ) Command ( 命令 ) Iterator ( 迭代子 ) Mediator ( 调停者 ) Memento ( 备忘录 ) Observer ( 观察者 ) State ( 状态 ) Strategy ( 策略 ) Visitor ( 访问者 ) Template Method ( 模版方法 ) Interpreter ( 翻译器 )

13 Topics Covered Today 2.3 Advanced Class Design –2.3.4 Design Patterns –2.3.5 Singleton Pattern –2.3.6 Strategy Pattern

14 One of a Kind In some applications, there are classes that should only be instantiated once. For instance: –system clock of an operating system; –one accounting system in a company; –object used for logging; –catalog of a library system –…

15 Answer These Questions? How could you create a single object? –New MyClass(); What if wanted to create another MyClass object? Could it call new on MyClass again? –Yes, if it is a public class. And if not? –Well, if it is not a public class,only classes in the same package can instantiate it. But they can still instantiate it more than once.

16 Answer These Questions?. Can we do this? –Yes. I suppose it is a class that can not be instantiated because it has a private constructor. Is there ANY object that could use this private constructor? –The code in MyClass is the only code that can call it. public class MyClass { private MyClass() { } }

17 Answer These Questions?.. What does this mean? –MyClass is a class with static method. –We can call the static method like this: MyClass.getInstance(); Why did you use MyClass instead of some object name? –Well, getInstance() is a static method, in other words, it is a CLASS method. We need to use the class name to reference a static method. public class MyClass { public static MyClass getInstance() { } }

18 Answer These Questions?… What if I put things together? Now can I instantiate a MyClass? –Yes Can you think of a second way to instantiate an object? –MyClass.getInstance(); public class MyClass { private MyClass() { } public static MyClass getInstance() { return new MyClass(); }

19 Answer These Questions?…. Can you finish the code so that only One instance of MyClass is ever created?

20 Solution public class ASingletonClass { private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static singleton getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here }

21 Solution public class ASingletonClass { private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static ASingletonClass getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here }

22 Solution public class ASingletonClass { private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static ASingletonClass getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here }

23 Solution public class ASingletonClass { private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static ASingletonClass getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here }

24 Solution public class ASingletonClass{ private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static ASingletonClass getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here } Lazy instantiation (延迟实例化) is important for resource intensive objects.

25 Solution public class ASingletonClass { private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static ASingletonClass getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here }

26 Singleton Pattern Defined The singleton pattern ensures that –only one instance of a class is created and –provides a method to access that one instance. Singleton pattern class diagram: Singleton -singletonInstance : Singleton -Singleton() +getSingletonInstance() : Singleton

27 Eagerly Created Singleton Instance public class Singleton { private static Singleton singletonInstance = new Singleton(); private Singleton() { } public static Singleton getSingletonInstance() { return singletonInstance; } JVM create the unique instance of the Singleton when class is loaded.

28 Singleton Pattern Example Class ICarnegieInfo contains the contact information for iCarnegie. Only one instance of class ICarnegieInfo can be created. ICarnegieInfo -singletonInstance : ICarnegieInfo -name: String -address: String -telephone: String -ICarnegieInfo() +getSingletonInstance() : ICarnegieInfo +getName():String +getAddress(): String +getTelephone(): String

29 Code Study Unit ICarnegieInfo.java Unit ICarnegieInfoDemo.java

30 ICarnegieInfoDemo.java import java.io.*; public class ICarnegieInfoDemo { private static PrintWriter stdOut = new PrintWriter(System.out, true); public static void main(String[] args) { ICarnegieInfo companyInfo = ICarnegieInfo.getSingletonInstance(); stdOut.println("Name: " + companyInfo.getName()); stdOut.println("Address: " + companyInfo.getAddress()); stdOut.println("Telephone: " + companyInfo.getTelephone()); }

31 Consequences The singleton pattern has the following benefits: –A singleton class can control how and when client code accesses the single instance. –A singleton class can be easily modified if requirements change and the application needs to limit the number of instances to a number other than one.

32 Topics Covered Today 2.3 Advanced Class Design –2.3.4 Design Patterns –2.3.5 Singleton Pattern –2.3.6 Strategy Pattern

33 Started with a simple SimUDuck app Joe works for a company that makes a highly successful duck pond simulation game, SimUDuck. The game can show a large variety of duck species swimming and making quacking sounds. The initial designers of the system used standard OO techniques and created one Duck superclass from which all other duck types inherit.

34 Duck Class Diagram quack() swim() display() // other duck-like methods Duck display() { // looks like a mallard } MallardDuck display() { // looks like a redhead } RedHeadDuck The display() method is abstract, since all duck subclass looks different.

35 Need the Ducks to FLY quack() swim() display() fly() // other duck-like methods Duck display() { // looks like a mallard } MallardDuck display() { // looks like a redhead } RedHeadDuck good or bad??

36 RubberDuck Duck quack() swim() display() fly() RubberDuck quack() { // override to squeak } display() RedHeadDuck display() MallardDuck display()

37 DecoyDuck quack() { // override to do nothing } display() fly() { // override to do nothing } 1. Code is duplicated across subclass. 2. Runtime behavior changes are difficult. RubberDuck quack() { // override} display() fly() { // override to do nothing }

38 Using Interface

39 Design Principle Identify the aspects of your application that vary and separate them from what stays the same. Duck Class Flying behaviors Quacking behaviors pull out what varies

40 Design Principle. Program to an interface, not an implementation. fly() > FlyBehavior fly() { // do nothing } FlyNoWay fly() { // implements duck flying } FlyWithWings

41 Program to interface Programming to an implementation would be: –Dog d = new Dog(); d.bark(); Programming to an interface/supertype would be: –Animal a = new Dog(); a.makeSound(); Assign concrete object at run time: –Animal a = getAnimal(); a.makeSound(); makeSound() > Animal makeSound() { meow(); } meow() {// meow sound} Cat makeSound() { bark();} bark() { // bark sound} Dog

42 Implementing the Duck Behavior quack() > QuackBehavior quack() { // rubber duck squesk } Squeak quack() { // implements duck quacking } Quack quack() { // do nothing } MuteQuack

43 Integrate the Duck Behavior Duck flyBehavior: FlyBehavior quackBehavior: QuackBehavior Duck() swim() display() performQuack() performFly() public abstract class Duck { QuackBehavior quackBehavior; FlyBehavior flyBehavior; public Duck() { } public void performQuack() { quackBehavior.quack(); } public void performFly() { flyBehavior.fly(); } public void swim() { System.out.println("All ducks float."); } } Each Duck has a reference to something that implements QuackBehavior interface Rather than handling the quack behavior itself, the Duck object delegates that behavior to the object referenced by quackBehavior

44 Implementing the Duck Subclass Duck flyBehavior: FlyBehavior quackBehavior: QuackBehavior Duck() swim() display() performQuack() performFly() MallardDuck MallardDuck() display() public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } public void display() { System.out.println(" I am a real mallard duck "); }

45 Define a set of Fly Behaviors //FlyBehavior.java public interface FlyBehavior { void fly(); } // FlyWithWings.java public class FlyWithWings implements FlyBehavior { public void fly() { System.out.println( " I am flying! " ); } } // FlyNoWay.java public class FlyNoWay implements FlyBehavior { public void fly() { System.out.println( " I can not fly. " ); } }

46 Define a set of Quack Behaviors // QuackBehavior.java public interface QuackBehavior { void quack(); } // Quack.java public class Quack implements QuackBehavior { public void quack() { System.out.println("Quack"); } } // MuteQuack.java public class MuteQuack implements QuackBehavior { public void quack() { System.out.println(" >"); } } // Squeak.java public class Squeak implements QuackBehavior { public void quack() { System.out.println("Squeak"); } }

47 Test Class // MiniDuckSimulator public class MiniDuckSimulator { public static void main (String[] args){ Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); } Quack I am flying!

48 Setting Behavior Dynamically Duck flyBehavior: FlyBehavior quackBehavior: QuackBehavior Duck() swim() display() performQuack() performFly() setFlyBehavior() setQuackBehavior() public abstract class Duck { QuackBehavior quackBehavior; FlyBehavior flyBehavior; public Duck() { } public void performQuack() { quackBehavior.quack(); } public void performFly() { flyBehavior.fly(); } public void swim() { System.out.println("All ducks float."); } public void setFlyBehavior(FlyBehavior fb) { flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; } }

49 ModelDuck Duck flyBehavior: FlyBehavior quackBehavior: QuackBehavior Duck() swim() display() performQuack() performFly() setFlyBehavior() setQuackBehavior() ModelDuck MadolDuck() display() public class ModelDuck extends Duck { public ModelDuck() { flyBehavior = new FlyNoWay(); quackBehavior = new MuteQuack(); } public void display() { System.out.println("I am a model duck"); }

50 MiniDuckSimulator2 //MiniDuckSimulator2 public class MiniDuckSimulator2 { public static void main (String[] args) { Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); Duck model = new ModelDuck(); model.performFly(); model.performQuack(); model.setFlyBehavior(new FlyWithWings()); model.setQuackBehavior(new Squeak()); model.performFly(); model.performQuack(); } Quack I am flying! I can not fly. > I am flying! Squeak

51 SimUDuck app Class Diagram

52 Another Example: TaxCalculator

53 Strategy Pattern "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it."

54 UML Class Diagram

55 Library Syatem

56 Requirement The library system could display the borrowers information with three formats: –Plain text –HTML –XML

57 Using Strategy Pattern

58 Exercise Program spec: –An action adventure game has many game characters, such as king, queen, knight and troll. Each character can make use of one weapon to fight at a time, but can change weapons at any time during the game. These weapons include knife, bow and arrow, sword, axe. Use strategy pattern to design UML class diagram for this program.

59 Summary Singleton pattern ensures that –only one instance of a class is created and –provides a method to access that one instance. Strategy pattern –define a family of algorithms, encapsulate each one, and make them interchangeable. –Strategy lets the algorithm vary independently from the clients that use it.