Documente Academic
Documente Profesional
Documente Cultură
Mod de realizare
Class Patterns
Focus pe relatii intre clase
Presupune reutilizare prin mostenire
Object Patterns
Focus pe relatii intre obiecte
Presupune reutilizare prin compozitie
Sursa: http://www.codeproject.com/Articles/12183/Design-Your-Soccer-Engine-andLearn-How-To-Apply-D
Clasificare sabloane
Riehle and Zullighoven: Understanding and Using
Patterns in Software Development
Conceptual Pattern
Descriere bazata pe termeni si concepte din domeniul aplicatiei
Design Pattern
descriere bazata pe constructii specifice proiectarii software: obiecte,
clase, mostenire, agregare
Programming Pattern (Programming Idiom)
descriere bazata pe constructii ale unui limbaj de programare.
References
Design Patterns: Elements of Reusable Object-Oriented Software,
Gamma, Helm, Johnson and Vlissides, Addison-Wesley, 1995
Design Patterns for Object-Oriented Software
Development,Wolfgang Pree, Addison-Wesley/ACM Press, 1995
Patterns of Software: Tales From The Software Community,Richard
P. Gabriel, Oxford University Press, 1996
Pattern Oriented Software Architecture : A System of Patterns,Frank
Buschmann (Editor), Wiley, 1996
Analysis Patterns: Reusable Object Models, Martin Fowler,AddisonWesley, 1997
AntiPatterns, Brown, Malveau, McCormick and Mowbray,Wiley,
1998
Design Patterns Explained, Alan Shalloway and James R. Trott,
Addison-Wesley, 2001
Core J2EE Patterns: Best Practices and Design Strategies, Alur,Crupi and
Malks, 2001
Design Patterns Java Workbook, Steven John Metsker, Addison-Wesley,
2002
Applied Java Patterns, Stephen Stelting and Olav Maassen,Prentice Hall,
2002
EJB Design Patterns: Advanced Patterns, Processes, and Idioms, Floyd
Marinescu, Wiley, 2002
Patterns Of Enterprise Application Archictecture, Martin Fowler, AddisonWesley, 2002
Bridge
Decupleaza o abstractie de posibilele ei implementari astfel incat sa poata
varia independent.
Context
Cand o anumita abstractiune poate avea mai multe variante de
implementare, de obicei se utilizeaza mostenirea: o clasa abstracta
defineste interfata abstractiunii, iar subclasele concrete o implementeaza
in diverse moduri.
Aceasta abordare nu este intotdeauna suficient de flexibila.
Prin mostenire o implementare este legata permanent de abstractiune si
acest lucru face foarte dificila modificarea independenta a abstractiunii si
a implementarii.
Structura
Abstraction:
defineste interfata abstractiunii;
detine o referinta spre un obiect de tip Implementor.
RefinedAbstraction: extinde interfata Abstraction
Implementor: defineste interfata pentru clasele ce contin implementari. Aceasta
interfata nu trebuie neaparat sa corespunda exact cu interfata Abstraction. De fapt,
cele 2 pot fi total diferite. De obicei Implementor ofera doar operatii primitive, iar
Abstraction defineste operatii de nivel mai inalt, bazandu-se pe acele primitive;
ConcreteImplem: implementeaza interfata Implementor.
Aplicabilitate:
se doreste evitarea legarii unei abstractiuni de implementarea sa.
Acest lucru se intampla de exemplu cand implementarea trebuie aleasa sau
modificata pe durata executiei;
Exemplu
Template Method
12
Aplicabilitate
Pentru a implementa partile invariante ale unui algoritm doar odata si a alasa
subclasele sa implementeze comportamenul care difera.
Atunci cand comportamenul comun mai multor clase trebuie sa fie evidentiat si
localizat intr-o clasa comuna pentru a evita duplicarea de cod.
13
class TemplateMethodApp {
MyApp app = new MyApp();
public void test() {
// The MyApp constr. does all the work.
// This just makes sure it will complete
// without throwing an exception.
}
public static void main(String args[]) { new
TemplateMethodApp().test();
}
}
14
15
16
17
AbstractCollection : A Collection that is neither a Set nor a List, such as a bag. At a minimum, you must
provide the iterator and the size method.
AbstractList : A List backed by a random-access data store (such as an array). At a minimum, you must
provide the positional access methods (get(int) and, optionally, set(int), remove(int), and add(int)) and the
size method. The abstract class takes care of listIterator (and iterator).
(public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> )
AbstractMap : A Map. At a minimum you must provide the entrySet view. This is typically implemented
with the AbstractSet class. If the Map is modifiable, you must also provide the put method.
19
Strategy
20
Strategy Structura
21
Strategy - Aplicabilitate
Cand mai multe clase difera doar in comportament. Strategy furnizeaza
un mod de a configura o clasa cu una sau mai multe functionalitati.
Cand este nevoie de mai multe variante ale unui algoritm. Strategy este
folosit atunci cand aceste variante sunt implementate ca o ierarhie de
clase de algoritmi.
22
Exemplu: sursahttp://a3ab771892fd198a96736e50.javacodegeeks.netdna-cdn.com/wpcontent/uploads/2013/08/Strategy-Pattern.png
Tratarea exceptiilor
24
Exceptii
exceptie != bug
25
Daca JVM sau mediul de executie detecteaza o cond. speciala, se arunca o exceptie
implicit !
26
try statement
try {
out.write(b);
}
catch (IOException e) {
System.out.println("Output Error");
}
finally {
out.close();
}
27
27
Exception Hierarchy
class java.lang.Throwable
class java.lang.Error
...
class java.lang.VirtualMachineError
class java.lang.InternalError
class java.lang.OutOfMemoryError
class java.lang.StackOverflowError
class java.lang.UnknownError
class java.lang.Exception
28
28
Throwable class
Method Summary
Throwable fillInStackTrace()
Fills in the execution stack trace.
Throwable getCause()
Returns the cause of this throwable or null if the cause is nonexistent or unknown.
String getLocalizedMessage()
Creates a localized description of this throwable.
String getMessage()
Returns the detail message string of this throwable.
StackTraceElement[] getStackTrace()
Provides programmatic access to the stack trace information printed by printStackTrace().
Throwable initCause(Throwable cause)
Initializes the cause of this throwable to the specified value.
void printStackTrace()
Prints this throwable and its backtrace to the standard error stream.
void printStackTrace(PrintStream s)
Prints this throwable and its backtrace to the specified print stream.
void printStackTrace(PrintWriter s)
Prints this throwable and its backtrace to the specified print writer.
void setStackTrace(StackTraceElement[] stackTrace)
Sets the stack trace elements that will be returned by getStackTrace() and printed by
printStackTrace() and related methods.
String toString()
Returns a short description of this throwable.
29
Clasa Exception
Constructor Summary
Exception()
Constructs a new exception with null as its detail message.
Exception(String message)
Constructs a new exception with the specified detail message.
Exception(String message, Throwable cause)
Constructs a new exception with the specified detail message
and cause.
Exception(Throwable cause)
Constructs a new exception with the specified cause and a
detail message of (cause==null ? null : cause.toString()) (which
typically contains the class and detail message of cause).
30
"chain" of exceptions
31
class java.lang.Exception
...
class java.lang.RuntimeException
class java.lang.ArithmeticException
class java.lang.ArrayStoreException
class java.lang.ClassCastException
class java.lang.IllegalArgumentException
class java.lang.IllegalThreadStateException
class java.lang.NumberFormatException
class java.lang.IllegalMonitorStateException
class java.lang.IllegalStateException
class java.lang.IndexOutOfBoundsException
class java.lang.ArrayIndexOutOfBoundsException
class java.lang.StringIndexOutOfBoundsException
class java.lang.NegativeArraySizeException
class java.lang.NullPointerException
class java.lang.SecurityException
class java.lang.UnsupportedOperationException
32
32
class java.lang.Exception
class java.io.IOException
class java.io.CharConversionException
class java.io.EOFException
class java.io.FileNotFoundException
class java.io.InterruptedIOException
class java.io.ObjectStreamException
class java.io.SyncFailedException
class java.io.UnsupportedEncodingException
class java.io.UTFDataFormatException
33
33
Declararea exceptiilor
checked,
unchecked (RuntimeExceptions)
34
class A {
public void foo() throws IOException {..}
}
class B extends A {
@Override
public void foo() throws SocketException {..} // allowed
@Override
public void foo() throws SQLException {..} // NOT allowed
}
//SocketException extends IOException, but SQLException does not.
35
import java.io.IOException;
class throwsExample {
char[] a; int position;
...
//explicitly throws an exception
int read() throws IOException {
if (position >= a.length)
throw new IOException();
return a[position++];
}
//implicitly throws an exception
String readUpTo(char terminator)
throws IOException {
StringBuffer s =
new StringBuffer();
while (true) {
int c = read();
// Can throw IOException
if (c == -1 || c == terminator) {
return s.toString(); }
s.append((char)c);
}
return s.toString();
}
36
36
Generare Exceptii
Instructiunea throw este folosita pentru a creea si a arunca o
exceptie. obiectul aruncat trebuie sa fie o instanta a unei subclase
a clasei Throwable.
java.lang.ArithmeticException: / by zero
at t.cap(t.java:16)
at t.doit(t.java:8)
at t.main(t.java:3)
Tratarea exceptiilor C#
42
43
Exemplu
using System;
public class MyCustomException :
System.ApplicationException
{
public MyCustomException(string message):
base(message)
{}
}
public class Test
{
public static void Main( )
{
Test t = new Test( );
t.TestFunc( );
}
public void TestFunc( )
{ try {
double a = 0;
double b = 5;
Console.WriteLine ({0} / {1} = {2}, a, b, DoDivide(a,b));
Console.WriteLine (This line may or may not print);
}
catch (System.DivideByZeroException e)
{
Console.WriteLine(DivideByZeroException! Msg: {0},
e.Message);
Console.WriteLine(HelpLink: {0},
e.HelpLink);
}
catch (MyCustomException e)
{
Console.WriteLine(\nMyCustomException! Msg:
{0},
e.Message);
Console.WriteLine(\nHelpLink: {0}\n,
e.HelpLink);
}
catch
{
Console.WriteLine(Unknown exception caught);
}}
public double DoDivide(double a, double b)
{ if (b == 0)
{ DivideByZeroException e = new
DivideByZeroException( );
e.HelpLink= http://www.greselifatale.com;
throw e;
}
if (a == 0)
{ MyCustomException e = new MyCustomException(
Cant have zero divisor);
e.HelpLink =
http://www.greselifatale.com/NoZeroDiviso
r.htm;
throw e;
}
return a/b;
44
}
catch(System.Exception e)
{
MyCustomException ex = new
MyCustomException(E3 -Custom
Exception Situation!,e);
throw ex;
}}
public void DangerousFunc2( )
{
try
{ DangerousFunc3( ); }
catch (System.DivideByZeroException e)
{
Exception ex =
new Exception(
E2 - Func2 caught divide by zero,e);
throw ex;
}
}
public void DangerousFunc3( )
{
try { DangerousFunc4( ); }
catch (System.ArithmeticException)
{ throw; }
catch (System.Exception)
{
Console.WriteLine(Exception handled here.);
}}
public void DangerousFunc4( )
{
throw new DivideByZeroException("E1 - DivideByZero
Exception");
}}
45
Checked exceptions
46
Comparatie
47
In Java:
interface Movie{
void Enjoy() throws PeopleTalkingException;
}
Implementarile metodei Movie.Enjoy( ) pot sa nu arunce nici o exceptie dar daca
arunca atunci singurul tip de exceptii verificate este PeopleTalkingException.
Avantaj : orice cod care foloseste interfata Movie si care trateaza exceptii de tip
PeopleTalkingExceptionse este garantata sa continue sa functioneze indiferent de
cum este aceasta interfata implementata.
Dezavantaj: uneori presupunerea initiala despre ce constituie o exceptie valida
este eronata.
48
Problema...
49
50