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