2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.1 TO DO: Create a new class which adds statistics to the dice This class should add.

Slides:



Advertisements
Similar presentations
2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/FundamentalConcepts.1 CSC7322: Object Oriented Development J Paul Gibson, A207
Advertisements

SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Design Patterns Pepper. Find Patterns Gang of Four created 23 Siemens published another good set x
Chapter 7 – Object-Oriented Design
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Abstraction, Inheritance, and Polymorphism in Java.
Object Oriented Design and UML
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Design Patterns.
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Implementing Design Patterns Using Java St. Louis Java Special Interest Group Eric M. Burke Object Computing, Inc. Presented on July 9, 1998 (updated July.
Ceg860 (Prasad)L6MR1 Modularity Extendibility Reusability.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
The Java Programming Language
CS 210 Introduction to Design Patterns September 7 th, 2006.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Object Oriented Software Development
2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/Design.1 CSC7322: Object Oriented Development J Paul Gibson, A207
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
Object Oriented Programming
Design Patterns: Elements of Reusable Object- Orientated Software Gamma, Helm, Johnson, Vlissides Presented By: David Williams.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Coming up: Inheritance
SEEM Java – Basic Introduction, Classes and Objects.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
CS 325: Software Engineering March 19, 2015 Applying Patterns (Part B) Code Smells The Decorator Pattern The Observer Pattern The Template Method Pattern.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
L10: Model-View-Controller General application structure. User Interface: Role, Requirements, Problems Design patterns: Model – View – Controller, Observer/Observable.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Kyung Hee University Class Diagramming Notation OOSD 담당조교 석사과정 이정환.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
The Observer Design Pattern Author :Erich Gamma, et al. Source :Elements of Reusable Object-Oriented Software Speaker : Chiao-Ping Chang Advisor : Ku-Yaw.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns: MORE Examples
Advanced Java Programming
Introduction to Design Patterns
Advanced ProgramMING Practices
Presentation transcript:

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.1 TO DO: Create a new class which adds statistics to the dice This class should add functionality to store the roll frequencies. You should implement a validation test (as well as running unit tests) as below: NOTE: Don’t forget to run regression tests

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.2 TO DO: Implement 2 different designs //using inheritance public class DiceWithStatistics1 extends Dice implements DiceWithStatisticsSpecification{ //… } //using composition public class DiceWithStatistics2 implements DiceWithStatisticsSpecification{ //… protected Dice dice; //… } If you have not developed your own solution code then you should try to understand my sample solution, which can be downloaded from the module web site: Dice-WithStatistics.zip

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.3 Specification using an interface package abstractions; public interface DiceWithStatisticsSpecification extends DiceSpecification{ public abstract int frequencyOfRoll(int side) throws IllegalArgumentException; public abstract boolean invariant(); public abstract void roll(); public String toString(); } Note: Javadoc comments – not on the transparency, but included in the code – are used to update the documentation for the statistics specification

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.4 TO DO: Implementation using inheritance /** * * This class extends the behaviour of the Dice} with * statistics for frequency of rolls * These statistics are viewable through an updated toString method * J Paul Gibson 1 * * Design decision - use inheritance to extend already existing Dice behaviour * Implementation decision - store the roll frequencies in an array of integers * */ public class DiceWithStatistics1 extends Dice implements DiceWithStatisticsSpecification { /** * Stores the number of times each side of the dice has been rolled */ protected int rollsFrequency [];

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.5 TO DO: Implementation using inheritance /** * Create a default dice and reset the roll frequencies for each side to be 0 * Increment the count for the numberOfDieWithStatistics */ public DiceWithStatistics1 (){ super(); rollsFrequency = new int [NUMBEROFSIDES]; resetFrequencies(); numberOfDieWithStatistics++; } /** * Create a dice and reset the roll frequencies for each side to be 0 * Increment the count for the numberOfDieWithStatistics sides can specify the number of sides * (within range of DiceSpecification#MINIMUM_numberOfSides}.. * DiceSpecification#MAXIMIM_numberOfSides}) */ public DiceWithStatistics1 (int sides){ super(sides); rollsFrequency = new int [NUMBEROFSIDES]; resetFrequencies(); numberOfDieWithStatistics++; }

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.6 TO DO: Implementation using inheritance public boolean invariant(){ if (rollsFrequency==null ) return false; if (rollsFrequency.length < NUMBEROFSIDES) return false; for (int i =0; i<NUMBEROFSIDES; i++) if (rollsFrequency[i] <0) return false; return super.invariant(); } QUESTION: Could/Should this invariant be implemented in an abstract class?

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.7 TO DO: Implementation using inheritance /** * rolls the dice, updates the lastRoll value and updates the frequency history */ public void roll(){ super.roll(); rollsFrequency[lastRoll()-1] = rollsFrequency[lastRoll()-1]+1; } /** the number of times the dice has rolled the specified side side specifies the side of the dice for which we wish to know * the number of rolls */ public int frequencyOfRoll(int side) throws IllegalArgumentException{ if (side MAXIMIM_numberOfSides) throw (new IllegalArgumentException("The number of sides specified is not valid")); return rollsFrequency[side-1]; }

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.8 TO DO: Implementation using inheritance /** a string representation of the current dice state, * including statistics */ public String toString(){ String str = super.toString(); str = str+"\n Frequencies:\n"; for (int i =0; i<dice.numberOfSides(); i++) str=str+"("+(i+1)+", "+rollsFrequency[i]+")"; str=str+"\n"; return str; } QUESTION: Could/Should this method be implemented in an abstract class?

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.9 TO DO: Implementation using composition /** * * This class extends the behaviour of the Dice} with statistics for * frequency of rolls * These statistics are readable through the toString method * J Paul Gibson 1 * * Design decision - use composition to re-use already existing Dice behaviour * Implementation decision - store the roll frequencies in an array of integers * */ public class DiceWithStatistics2 implements DiceSpecification{ protected Dice dice; /** * The number of dieWithStatistics objects that are currently instantiated * We decrement this value when a DiceWithStatistics1 destructor is called - */ protected static int numberOfDieWithStatistics = 0; /** * Stores the number of times each side of the dice has been rolled */ protected int rollsFrequency [];

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.10 TO DO: Implementation using composition /** * Create a new DiceWithStatistics2 and reset the roll frequencies for each side to be 0 * The number of sides is set by default to DiceSpecification#DEFAULT_numberOfSides} * Increment the count for the numberOfDieWithStatistics */ public DiceWithStatistics2 (){ dice = new Dice(); rollsFrequency = new int [dice.numberOfSides()]; resetFrequencies(); numberOfDieWithStatistics++; } /** * Create a new DiceWithStatistics2 and reset the roll frequencies for each side to be 0 * Increment the count for the numberOfDieWithStatistics sides can specify the number of sides * (within range of DiceSpecification#MINIMUM_numberOfSides}.. * DiceSpecification#MAXIMIM_numberOfSides}) * If it is not in range use the default number of sides DiceSpecification#DEFAULT_numberOfSides}) */ public DiceWithStatistics2 (int sides){ dice = new Dice(sides); rollsFrequency = new int [dice.numberOfSides()]; resetFrequencies(); numberOfDieWithStatistics++; }

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.11 TO DO: Implementation using composition public int lastRoll (){ return dice.lastRoll();} public int numberOfSides(){ return dice.numberOfSides();} public int numberOfRolls(){ return dice.numberOfRolls();} /** * Decrement the count for the number of current DiceWithStatistics that are instantiated */ protected void finalize() throws Throwable{ numberOfDieWithStatistics--;}

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.12 TO DO: Implementation using composition public boolean invariant(){ if (rollsFrequency==null ) dice.invariant(); else for (int i =0; i<dice.numberOfSides(); i++) if (rollsFrequency[i] <0) return false; return true; } public void roll(){ dice.roll(); rollsFrequency[lastRoll()-1] = rollsFrequency[lastRoll()-1]+1; } public int frequencyOfRoll(int side) throws IllegalArgumentException{ if (side numberOfSides()) throw (new IllegalArgumentException("The number of sides specified is not valid")); return rollsFrequency[side-1]; }

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.13 TO DO: Implementation using composition /** a string representation of the current dice state, including statistics */ public String toString(){ String str = dice.toString(); str = str+"\n Frequencies: \n"; for (int i =0; i<dice.numberOfSides(); i++) str=str+"("+(i+1)+", "+rollsFrequency[i]+")"; str=str+"\n"; return str; } Note: this is very similar to the toString method in the inheritance based design /** a string representation of the current dice state, * including statistics */ public String toString(){ String str = super.toString(); str = str+"\n Frequencies: \n"; for (int i =0; i<dice.numberOfSides(); i++) str=str+"("+(i+1)+", "+rollsFrequency[i]+")"; str=str+"\n"; return str; } QUESTION: how to factor out the cut-and-paste code?

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.14 TO DO: Write tests for both designs Unit tests Validation tests Maximise re-use Maximise re-usability Minimize cut-and-paste programming

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.15 TO DO: Create 2 different terminal/console views The frequencies can either be displayed vertically or horizontally. (OPTIONAL: If the frequency values are bigger than the height/width of the screen then you should scale them in order to occupy as much of the screen as possible. The screen size should be stored in constant variables HEIGHT and WIDTH.) 1 |******** 2 |****** 3 |*** 4 |**** 5 |****** 6 |** 7 |*** 8 |** 9 |***** 10 | 11 |***** 12 |** 13 |******** 14 |***** 15 |********* * * * * ** * * * ** * * * *** ** ** * * *** ***** * * * *** ********* ***** DISCUSSION: How to best include these views in the design?

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.16 The consequences of the initial design decision– Choosing to implement a DiceWithStatistics as a subclass of Dice is a design decision that may have consequencies on later stages of the development. The alternative re-use mechanism was to design a DiceWithStatistics class/object to have a Dice component class/object. This also may have consequencies on later stages of the development DISCUSSION: What are the possible consequences (positive and negative)? CLUE: You may have seen them when we considered the different views OBSERVERS: We may wish to create different views that automatically update when the state of the models changes

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.17 The Observer Design Pattern This pattern is among the most useful for object-oriented software design. It is a key part of the MVC pattern - the JDK itself makes heavy use of a variant of this pattern in the 1.1 AWT event delegation model, and the Swing libraries also facilitate its use The JDK libraries also provide a reusable implementation of the pattern in the form of the java.util.Observer interface and the java.util.Observable class.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.18 The Observer Design Pattern: UML The idea of the pattern is to model a one-to-many dependency without tightly coupling the observed object with its many observers. When the observed object changes in some interesting way it can automatically notify all of its observers without knowing them directly

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.19 Weaknesses Unfortunately, a number of weaknesses have been identified in the JDK's Observer/Observable classes. These weaknesses significantly limit the reusability and power of the classes, which is a shame since powerful reusability is a big part of what object oriented design is all about. Most of the weaknesses are due to the fact that java.util.Observable is a class rather than an interface; or rather, that it is a class without a corresponding interface. This implies that the only way to reuse Observable is to subclass it. You can't take an existing class and tack on the role of Observable by having it implement an Observable interface because there is no Observable interface.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.20 Weaknesses What if you have a class that is already in a class hierarchy and also needs to play the role of an Observable? Since Java doesn't support multiple inheritance, you're out of luck. That class cannot extend from Observable because it is already extending from some other class. It also means that you are stuck with the one and only implementation of Observable in java.util.Observable. For a variety of reasons, you may want to use an alternate implementation - e.g., to do the notification in a separate thread or in a particular order. You may even want to vary the implementation of Observable at runtime. There is no Observable interface for your alternate implementations to implement. You cannot reuse Observable by composition so you cannot vary the composed Observable implementation at runtime.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.21 Weaknesses The designers of the Observable class broke two general principles of object- oriented design with Java: 1.The first principle is to design with interfaces rather than classes. Whenever possible, avoid committing yourself to a particular implementation of an interface. 2.The second principle is to favor reuse by composition over reuse by inheritance unless a class hierarchy is clearly indicated. By omitting an Observable interface and making some of its methods protected, the designers made it impossible to reuse Observable by composition.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.22 Weaknesses A minor weakness in Observable is the necessity to call setChanged() before notifySubscribers(). The intention there seems to be to eliminate needless notifications in cases where there is no interesting change to the Observable. There may be situations in which this two-stage notification is appropriate, but it isn't the simplest case and programmers shouldn't be forced to use this implementation in all situations. Also, setChanged() is protected, further reinforcing the necessity to reuse the class only by inheritance.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.23 Weaknesses The main weakness in the Observer interface is its tight coupling with the Observable class. The first parameter to the update() method is unnecessarily typed as an Observable. If it were typed more generally as a simple Object, the Observer interface would be more reusable. It then could be used with any Observable implementation or even in any situation, completely unrelated to Observer/Observable, which called for a void method with two Object parameters.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.24 Possible Solutions The general opinion is that one should re-use a better/improved Observer. Many such improved Observers exist (the versionby Coad and Mayfield is perhaps the best known) You should be able to write your own! References Gamma, E., Johnson, R. and Vlissides, J., "Design Patterns: Elements of Object-Oriented Architecture", Addison-Wesley, Reading, MA, Coad, P. and Mayfield, M., "Java Design: Building Better Apps and Applets", Yourdon Press, Upper Saddle River, NJ, 1997.

2013: J Paul GibsonTSP: Object Oriented DevelopmentCSC7322/DesignII.25 TO DO Write your own Observable interface Using this interface, make an Observable Dice. Make 2 views: Horizontal and Vertical histograms (you should already have the code for these!) Let these views observe the observable Dice (and update their output accordingly) QUESTION: did your code maximise re-use and re-usability? If not, restructure the code (design)