Overview. Another application of Interfaces: the Strategy Design Pattern. n Java interfaces

Similar documents
Bruce Eckel, Thinking in Patterns with Java, cf. José Valente de Oliveira 10-1

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

JCF: case studies. Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf.

Java net programming II

Interfaces Java. Overview. n Java interfaces. q Introduction. q Sintaxe. q UML notation. q Multi-inheritance of interfaces

Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Streams. Overview. The notion of stream Java I/O streamhierarchy Files, and file access using streams Serialization Sockets

Τεχνολογία Λογισμικού

Goals of the Lecture UML Implementation Diagrams

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Threads and Concurrency in Java: Part 1

Threads and Concurrency in Java: Part 1

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Today s objectives. CSE401: Introduction to Compiler Construction. What is a compiler? Administrative Details. Why study compilers?

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Exercise Set: Implementing an Object-Oriented Design

Schema for the DCE Security Registry Server

Structuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Priority Queues. Binary Heaps

! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.

Computers and Scientific Thinking

n We have discussed classes in previous lectures n Here, we discuss design of classes n Library design considerations

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

From last week. Lecture 5. Outline. Principles of programming languages

Topics. Instance object. Instance object. Fundamentals of OT. Object notation. How do objects collaborate? Pearson Education 2007 Appendix (RASD 3/e)

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

CSE 417: Algorithms and Computational Complexity

Java Inheritance. Class ADT (Abstract Data Type) Interface. Classes implement the concept of ADT: Interfaces define interaction contracts: Rui Moreira

CIS 121. Introduction to Trees

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Python Programming: An Introduction to Computer Science

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Java Expressions & Flow Control

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Data Structures and Algorithms. Analysis of Algorithms

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Introduction to Pattern Oriented Analysis and Design (POAD) Instructor: Dr. Hany H. Ammar Dept. of Computer Science and Electrical Engineering, WVU

CS 11 C track: lecture 1

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5.

CS 111: Program Design I Lecture 19: Networks, the Web, and getting text from the Web in Python

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Avid Interplay Bundle

BEA Tuxedo. Using the CORBA Name Service

An introduction to Java II

Package RcppRoll. December 22, 2014

Lecture 5. Counting Sort / Radix Sort

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

Abstract Data Types (ADTs) Stacks. The Stack ADT ( 4.2) Stack Interface in Java

Examples and Applications of Binary Search

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

Chapter 4 The Datapath

Goals of the Lecture Object Constraint Language

Computer Architecture ELEC3441

Analysis of Algorithms

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

n Haskell n Covered syntax, lazy evaluation, static typing n Algebraic data types and pattern matching n Type classes n Monads and more n Types

A SOFTWARE MODEL FOR THE MULTILAYER PERCEPTRON

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

Architectural styles for software systems The client-server style

Programming with Shared Memory PART II. HPC Spring 2017 Prof. Robert van Engelen

Ones Assignment Method for Solving Traveling Salesman Problem

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Chapter 4 Threads. Operating Systems: Internals and Design Principles. Ninth Edition By William Stallings

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Lazy Type Changes in Object-oriented Database. Shan Ming Woo and Barbara Liskov MIT Lab. for Computer Science December 1999

Module 8-7: Pascal s Triangle and the Binomial Theorem

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

n Explore virtualization concepts n Become familiar with cloud concepts

Recursive Procedures. How can you model the relationship between consecutive terms of a sequence?

The Magma Database file formats

Alpha Individual Solutions MAΘ National Convention 2013

Baan Tools User Management

The isoperimetric problem on the hypercube

CMPT 125 Assignment 2 Solutions

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

Computational Geometry

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

ifs considered Harmful

WYSE Academic Challenge Sectional Computer Science 2005 SOLUTION SET

Compiling and executing managed code

EVALUATION OF TRIGONOMETRIC FUNCTIONS

Transcription:

Aother applicatio of Iterfaces: the Strategy Desig Patter Erich Gamma, Richard Helm, Ralph Johso, Joh Vlissides, Desig Patters Elemets of Reusable Object- Orieted Software, Addiso-Wesley, 1995, AKA GoF Bruce Eckel, Thikig i Patters with Java, cf. http://www.midview.et/books/tipatters/ jvo@ualg.pt José Valete de Oliveira 12-1 Overview Java iterfaces q Itroductio q Sitaxe q UML otatio q Multi-iheritace of iterfaces q (Some) Java pre-defied iterfaces q Desig patter: Strategy jvo@ualg.pt José Valete de Oliveira 11-2 1

Previously o POO: The Quicksort abstract class @SuppressWarigs( uchecked ) abstract class Quicksort { private Comparable[] data; public fial void quicksort (Comparable[] d) { data = d; quicksort(0, data.legth-1); Java pre-defied iterfaces Iterface Comparable<T> { /** Aswer a egative iteger if the receiver is lower tha the argumet obj; aswer 0 if both receiver ad obj are equal; aswer a positive iteger is receiver is greater tha obj */ it compareto(t obj); @Deprecated iterface Comparable { /** Aswer a egative iteger if the receiver is lower tha the argumet obj; aswer 0 if both receiver ad obj are equal; aswer a positive iteger is receiver is greater tha obj */ it compareto(object obj); jvo@ualg.pt José Valete de Oliveira 11-4 2

Example /** @versio 3.0 */ class Fractio implemets Comparable<Fractio> { private it um, de; // public it compareto (Fractio f) { double q = (double) um / (double) de ; double fq = (double) f.um /(double) f. de ; retur ((it) Math.sigum(q fq)); jvo@ualg.pt José Valete de Oliveira 11-5 Example public class Mai { public static void mai(strig[] args) { Fractio [] a = {ew Fractio(1, 7), ew Fractio(5, 2), ew Fractio(1, 2) ; ProbQuickSort<Fractio> pqs; pqs = ew ProbQuickSort<Fractio>(); pqs.quicksort(a); for(it i=0; i< a.legth; i++ ) System.out.pritl (a[i]); jvo@ualg.pt José Valete de Oliveira 11-6 3

Pre-defied Java iterfaces iterface Cloeable { jvo@ualg.pt José Valete de Oliveira 11-7 Mai methods of abstract superclass Object protected Object cloe() throws CloeNotSupportedExceptio public boolea equals(object obj) protected void fialize() throws Throwable public fial Class<?> getclass() public Strig tostrig() jvo@ualg.pt José Valete de Oliveira 11-8 4

Example Iterface IStack { it DEFAUL_SIZE = 10; // class AStack implemets IStack, Cloeable { public AStack() { this(default_size); public Object cloe() { // TODO // jvo@ualg.pt José Valete de Oliveira 11-9 Check poit: where is the error i the class Cliet? class Poit implemets IPoit { private it x, y; public Poit (it a, it b) {setx(a); sety(b); public it getx() {retur x; public it gety() {retur y; public void setx(it a) { assert a>=0; x=a; public void sety(it b) public { assert class b>=0; Cliet x=b; { public it dist(poit p) { public static void mai(strig[] args) { it dx = x p.getx(); IPoit A, B; it dy = y p.gety(); A = ew IPoit(1, 1); retur (it) Math.sqrt(dx*dx+dy*dy); B = ew IPoit(4, 2); System.out.pritl(A.dist(B)); jvo@ualg.pt José Valete de Oliveira 11-10 5

The Strategy Desig Pater, or aother commo use for iterfaces jvo@ualg.pt José Valete de Oliveira 11-11 Strategy desig patter, motivatio jvo@ualg.pt José Valete de Oliveira 12-12 6

Previously o POO: The Quicksort abstract class @SuppressWarigs( uchecked ) abstract class Quicksort { private Comparable[] data; // Previously o POO: Java pre-defied iterfaces Iterface Comparable<T> { /** Aswer a egative iteger if the receiver is lower tha the argumet obj; aswer 0 if both receiver ad obj are equal; aswer a positive iteger is receiver is greater tha obj */ it compareto(t obj); jvo@ualg.pt José Valete de Oliveira 11-14 7

Previously o POO: The Quicksort abstract class public abstract class Quicksort // /** For comparisos, the compareto method from iterface Comparable<T> is used. */ protected fial boolea less(it i, it j) { T di = data.get(i); T dj = data.get(j); retur (di.compareto(dj) < 0); jvo@ualg.pt José Valete de Oliveira 11-15 Previously: Sortig fractios public class Mai { public static void mai(strig[] args) { Fractio [] a = {ew Fractio(1, 7), ew Fractio(5, 2), ew Fractio(1, 2) ; ProbQuickSort<Fractio> pqs; pqs = ew ProbQuickSort<Fractio>(); pqs.quicksort(a); for(it i=0; i< a.legth; i++ ) System.out.pritl (a[i]); jvo@ualg.pt José Valete de Oliveira 11-16 8

Previously: Fractio implemets Comparable<T> class Fractio implemets Comparable<Fractio> { private it um, de; // public it compareto (Fractio f) { double q = (double) um / (double) de ; double fq = (double) f.um /(double) f. de ; retur ((it) Math.sigum(q fq)); jvo@ualg.pt José Valete de Oliveira 11-17 Strategy java example public abstract class Quicksort // protected fial boolea less(it i, it j) { T di = data.get(i); T dj = data.get(j); retur (di.compareto(dj) < 0); iterface Comparable<E> { it compareto(e e); class Fractio implemets Comparable<Fractio> { // public it compareto (Fractio f) { double q = (double) um / (double) de ; double fq = (double) f.um /(double) f. de ; retur ((it) Math.ceil(q fq)); jvo@ualg.pt José Valete de Oliveira 12-18 9

The same example i UML {abstract Quicksort # less(it i, it j) <<iterface>> Comparable<E> + compareto(e e) Fractio + compareto (Fractio f) jvo@ualg.pt José Valete de Oliveira 12-19 Strategy itet Defie a family of algorithms, ecapsulate each oe, ad make them iterchageable. Capture the abstractio i a iterface that ca be implemeted by idepedet classes. jvo@ualg.pt José Valete de Oliveira 12-20 10

Strategy usage Use this patter whe a object should be parametrized with oe of several algorithms that ca be represeted by a sigle iterface Strategy allows oe of a family of algorithms to be selected o-the-fly at rutime. jvo@ualg.pt José Valete de Oliveira 12-21 Strategy - structure jvo@ualg.pt José Valete de Oliveira 12-22 11

The same example agai {abstract Quicksort # less(it i, it j) <<iterface>> Comparable<E> + compareto(e e) Fractio + compareto (Fractio f) jvo@ualg.pt José Valete de Oliveira 12-23 Strategy Brief discussio The usage of the Strategy Desig patter avoids the employmet of coditioal cotrol structures that would make code hard to read ad to maitai Cliet eeds to be aware of the differet available strategies I some case, both Strategy ad Template Methods ca be used Typically, Strategy is more flexible while Template method is more eficiet jvo@ualg.pt José Valete de Oliveira 12-24 12

Program to a iterface ot for a implemetatio jvo@ualg.pt José Valete de Oliveira 12-25 Check poit: We foud the code i this ad i the ext slide i the et public class Mai { public static void mai(strig [] a) throws FileNotFoudExceptio { Strig s = "a Strig"; FileDataHadler.write("test", s, "html"); FileDataHadler.write("test", s, "xml"); jvo@ualg.pt José Valete de Oliveira 12-26 13

Check poit: how to improve the Quality of this code? class FileDataHadler { public static void write(strig fileame, Strig text, Strig selector) throws FileNotFoudExceptio { fileame += '.' + selector; PritWriter out = ew PritWriter(ew File(fileame).getAbsoluteFile()); if (selector.comparetoigorecase("html")==0) out.prit("<div><h1> " + text + "</h1></div>"); else if (selector.comparetoigorecase("xml")==0) out.prit("<?xml versio="+'"'+"1.0"+'"'+" ecodig="+'"'+"iso- 8859-1"+'"'+"?> <data>" + text + "</data>"); else { System.err.pritl("Ivalid Selector"); System.exit(1); jvo@ualg.pt José Valete de Oliveira 12-27 Recall the structure of Strategy jvo@ualg.pt José Valete de Oliveira 12-28 14

Applyig the Strategy Desig Patter: 1 Defie the Strategy Iterface iterface IDisplayCotets{ Strig display(strig s); Strig fileextesio(); jvo@ualg.pt José Valete de Oliveira 12-29 Applyig the Strategy Desig Patter: 2 Defie the Cotext class class FileDataHadler { public static void write(strig fileame, Strig text, IDisplayCotets i) throws FileNotFoudExceptio { fileame += i.fileextesio(); PritWriter out = ew PritWriter(ew File(fileame).getAbsoluteFile()); out.prit(i.display(text)); out.close(); jvo@ualg.pt José Valete de Oliveira 12-30 15

The ew FileDataHadler is ow much more clear tha the origial class FileDataHadler { public static void write(strig fileame, Strig text, Strig selector) throws FileNotFoudExceptio { fileame += '.' + selector; PritWriter out = ew PritWriter(ew File(fileame).getAbsoluteFile()); if (selector.comparetoigorecase("html")==0) out.prit("<div><h1> " + text + "</h1></div>"); else if (selector.comparetoigorecase("xml")==0) out.prit("<?xml versio="+'"'+"1.0"+'"'+" ecodig="+'"'+"iso- 8859-1"+'"'+"?> <data>" + text + "</data>"); else { System.err.pritl("Ivalid Selector"); System.exit(1); jvo@ualg.pt José Valete de Oliveira 12-31 Applyig the Strategy Desig Patter: 3 Write the cocrete class that implemets the Strategy iterface class StrategyHTML implemets IDisplayCotets { // retur cotets of data file as HTML public Strig display(strig s){ retur "<div><h1>cotets of data file, formatted as HTML</h1><p>" + s + "</p></div>"; public Strig fileextesio() { retur ".html"; // defie 'StrategyXML' class class StrategyXML implemets IDisplayCotets { // retur cotets of data file as XML public Strig display(strig s) { retur "<?xml versio="+'"'+"1.0"+'"'+" ecodig="+'"'+"iso-8859-1"+'"'+"?> <data><filedata>" + s + "</filedata></data>"; public Strig fileextesio() { retur ".xml"; jvo@ualg.pt José Valete de Oliveira 12-32 16

Applyig the Strategy Desig Patter: 4 Let the cliet decide o the strategy to use. public class Mai { public static void mai(strig [] a) throws FileNotFoudExceptio { Strig s = astrig"; IDisplayCotets d = ew StrategyHTML(); FileDataHadler.write("test", s, d); d = ew StrategyXML(); FileDataHadler.write("test", s, d); jvo@ualg.pt José Valete de Oliveira 12-33 Summary Java iterfaces q A itroductio q Sitaxe q UML otatio q Multi-iheritace of iterfaces q (Some) Java pre-defied iterfaces q Desig patter: Strategy jvo@ualg.pt José Valete de Oliveira 12-34 17

Namespaces ad Java Packages José Valete de Oliveira Overview Namespaces Java Packages q Usig ad resolvig packages Packages i UML q q Notatio Relatioships jvo@ualg.pt José Valete de Oliveira 13-36 18

Namespaces A ame space is ay laguage costruct that cotais defiitios ad a regio of the program where those defiitios apply. A ame space has a ame that ca be used to access the defiitios from outside of the costruct. jvo@ualg.pt José Valete de Oliveira 13-37 Why amespaces? To use simple, easy to remember ames i differet cotexts To miimize chaces of ame clashes whe usig multiple libraries To keep mai amespace clea jvo@ualg.pt José Valete de Oliveira 13-38 19

Package A package is a groupig of related elemets providig access protectio ad ame space maagemet. The elemets ca be classes, iterfaces, eumeratios, aotatio types, or aother packages. jvo@ualg.pt José Valete de Oliveira 13-39 Java Packages Orgaize classes i libraries Structure ame space for classes Restrict visibility Ca be ested Some of the core packages of Java: q q q q q java.lag java.util java.io java.et java.applet jvo@ualg.pt José Valete de Oliveira 13-40 20

Usig ames defied withi a package /** @versio 0.0 */ class Mai { public static void mai(strig [] args) { java.util.scaer s = ew java.util.scaer(system.i); it = s.extit(); // /** @versio 1.0 */ import java.util.scaer; class Mai { public static void mai(strig [] args) { Scaer s = ew Scaer(System.i); it = s.extit(); //. jvo@ualg.pt José Valete de Oliveira 13-41 Usig ames defied withi a package /** @versio 1.1 */ import java.util.*; class Mai { public static void mai(strig [] args) { Scaer s = ew Scaer(System.i); it = s.extit(); List<Fractio> = ew ArrayList<Fractio>(); //. jvo@ualg.pt José Valete de Oliveira 13-42 21

Uique package amig scheme A class programmed at the domai deei.fct.ualg.pt should be defied i the package pt.ualg.fct.deei i.e., the domai is reversed ad subdomais become packages) This guaratees that o other orgaizatio will create a class whose ame coflicts with classes developed at deei.fct.ualg.pt. jvo@ualg.pt José Valete de Oliveira 13-43 Defiig packages // File: Poit.java package pt.ualg.fct.deei.graphiceditor; public class Poit { /* */ Covetio: package ames start with a lower case class A { /* */ class B { /* */ jvo@ualg.pt José Valete de Oliveira 13-44 22

Defiig packages // File: File: Rectagle.java package pt.ualg.fct.deei.graphiceditor; public class Rectagle exteds Polygo { // import pt.ualg.fct.deei.graphiceditor.poit; public class Mai { public static void mai(strig[] args) { Poit p = ew Poit(); // jvo@ualg.pt José Valete de Oliveira 13-45 Recall: cotets of a.java file 1. Optioally, oe package directive; 2. Zero or more import directives; 3. Oe or more class / iterface defiitios, oe of them beig public ad with the same ame of the file jvo@ualg.pt José Valete de Oliveira 13-46 23

Package compilig Package ames map directly to subdirectories Whe compiled, the package structure is physically represeted usig a directory tree: q The.class file for the class pt.ualg.fct.deei.graphiceditor.poit will be saved at: pt/ualg/fct/deei/graphiceditor/poit.class jvo@ualg.pt José Valete de Oliveira 12-47 Resolvig packages i rutime Due to packages,.class files ca ow exist withi a large umber of directories For performace reasos, the ClassLoader (from JVM) must have a quick way of resolvig a fully qualified class referece to.class file. The ClassLoader uses a eviromet variable called CLASSPATH to fid the directories cotaiig.class files jvo@ualg.pt José Valete de Oliveira 12-48 24

Resolvig packages i rutime My classpath.;c:\programas\jade\lib\jade.jar;c:\programas\jade\lib\jadetools.jar;c:\programas\jade\iiop.jar;c:\programas\jade\lib\http.jar;c:\ Programas\Jade\\lib\commos-codec\commoscodec- 1.3.jar;c:\programas\jadex- 0.96\lib\jadex_rt.jar;c:\programas\jadex-0.96\lib\jibx- ru.jar;c:\programas\jadex-0.96\ib\xpp3.jar;c:\programas\jadex- 0.96\lib\uggets.jar;c:\programas\jadex- 0.96\lib\jaio.jar;c:\programas\jadex- 0.96\lib\jadex_stadaloe.jar;c:\programas\jadex- 0.96\lib\jadex_tools.jar;c:\programas\jadex- 0.96\lib\GraphLayout.jar;c:\programas\jadex-0.96\lib\jhall.jar jvo@ualg.pt José Valete de Oliveira 12-49 UML otatio for packages 25

UML otatio for packages jvo@ualg.pt José Valete de Oliveira 12-51 UML packages: relatioships Package A Package B «imports» Package C jvo@ualg.pt José Valete de Oliveira 12-52 26

UML packages: importig jvo@ualg.pt José Valete de Oliveira 12-53 To take away Namespaces Java Packages q Usig ad resolvig packages Packages i UML q q Notatio Relatioships jvo@ualg.pt José Valete de Oliveira 13-54 27