structural patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralpatterns-jz.pdf ·...

53
JPU (ALJAZEERA PRIVATE UNIVERSITY) د. باسم قصيبة1 Structural Patterns

Upload: others

Post on 28-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 1

Structural Patterns

Page 2: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 2

Structural Patterns (1)

تحدد كيف يتم تجميع األغراض

الـPatterns في هذا الصنف متممين لبعضهم البعض. Adapter

Convert the interface of a class into another interface clients expect.

Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

دؼو غشض افق ألخش

Bridge Decouple an abstraction from its implementation so that the two can vary

independently.

فصو ث ردشذ غشض رفزار

Composite Compose objects into tree structures to represent part-whole hierarchies.

Composite lets clients treat individual objects and compositions of objects uniformly.

ؼزذ ػي أغشاض ثذائخ نبد ب

Page 3: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 3

Structural Patterns (2)

Decorator Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending

functionality. ضف خذبد ىيغشض دبنب ثشنو ػد

Facade Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem

easier to use. خف اىجخ اىؼقذح ىظب

Flyweight Use sharing to support large numbers of fine-grained objects

efficiently. أغشاض صغشح اىحد نشسخ ىزن زشبسمخ

Proxy Provide a surrogate or placeholder for another object to control access

to it. غشض حدت آخش

Page 4: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 4

Structural Design Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.

Page 5: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 5

Composite

Compose objects into tree structures to represent part-whole hierarchies.

Composite lets clients treat individual objects and compositions of objects

uniformly.

Page 6: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 6

Composite –Example 1

Awt/Swing Components and their method of repaint().

Page 7: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 7

Composite –Example 2

: كما في الشكل التالي Components نريد نمذجة دارات منطقية اعتبارا من

.يل ػي األمثش دخي خشج حذ Component اىـ

. Component دت أ زصو إى ذخو Component أخو ثبء داسح فإ خشج

. ق دخي Component زا زقف ػي ع اىـ . ن أ ن فؼبال أ ال Component خشج اىـ

.قه إ دخال فؼبال إرا مب صال إى خشج فؼبه غش فؼبه إرا مب صال إى خشج غش فؼبه

.ال يل دخال خشخ دب فؼبه Generator اىـ

.ال يل خشخب ضئخ إرا مبذ فؼبىخ Light اىـ

.{فؼبال }أ صال { غش فؼبه}ن أ ن فزحب Switch اىـ

. ب ثخشج حذ دخو حذ Switch اىـ Not اىـ

.Or اىـ And ثذخي خشج حذ مبىـ Components نب أ ش أضب

إرا ى زصو اىذخو ثـ . اىزصو ث Component زؼيق ػب ثبىـ Component دخو اىـ

null اىز يل دخال Component إرا حىب حسبة خشج . null ف Component

.Exception NullComponentInputException فإ دت سفغ

Gen

erat

or

Sw

itch

Not

And

Or

Lig

ht

Page 8: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 8

Composite –Example 2

Componentboolean isActive()

Component_1_Out

Component_1_in_1_Out Component_2_in_1_Outin1, in2in1

And

isActive()Or

isActive()Not

isActive()

Generator

isActive()

Switch

isActive()

Light

isLighted() in

Page 9: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 9

Structural Design Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.

Page 10: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 10

Decorator (1)

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Ex : I/O Streams in Java

Page 11: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 11

Decorator (2)

Page 12: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 12

Decorator (3)

Structure

When to use :

to add responsibilities to individual objects dynamically and transparently.

for responsibilities that can be withdrawn. when extension by subclassing is impractical. Sometimes a large

number of independent extensions are possible and would produce an explosion of subclasses to support every combination.

Page 13: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 13

Example of debugger(1/12) :

Decorator + Composite + Singleton

حو سء ثبسزخذاprintln("info about the bug")

اسزخذا اىاخخDebugger

DebuggerToScreen

WithoutDebugger

DebuggerToFile

رحس إضبف ثبسزخذاDeuggerToStream

DebuggerToScreen

DebuggerToFile

DebuggerInWindow

Usage

Page 14: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 14

Example of debugger(2/12) :

Decorator + Composite + Singleton

اىحو اىسئpublic class BadSolution{public static void main(String[] args){System.out.println(« Begin of program.");

System.out.println("Begin of For.");

for(int i=0; i<10; i++){System.out.println("Begin of step i=" + i);// ...System.out.println("End of step i=" + i);

}

System.out.println("End of For.");

//// Several ohers thousands of System.out.println().//

System.out.println("End of program.");}

}

ىبرا ز اىحو سئإصاىخ اىزقح

>>>إصاىخ اىجشبح

رغش اىزقح ح يف أ إضبفخ...أ ... ؼيبد إضبفخ أ

>>>رغش اىجشبح

Page 15: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 15

Example of debugger (3/12) :

Decorator + Composite + Singleton

public interface Debugger

{

public void display(String message);

}

public class DebuggerToScreen implements Debugger {

public void display(String message)

{

System.out.println(message);

}

}

public class DebuggerToFile implements Debugger {

public DebuggerToFile(String nnameFile) throws

FileNotFoundException {

FileOutputStream f = new FileOutputStream (nameFile);

sf = new PrintStream (f);

}

public void display(String message)

{sf.println(message);}

}

public class WithoutDebugger implements

Debugger {

public void display(String message)

{ //nothing .... }

}

اسزخذا اىاخخDebugger

فصو االسزخذا ػ مفخ رفز= اىذف

ن إضبفخ ظبئف خذذح ػذ اىحبخخ

Page 16: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 16

Example of debugger (4/12) :

Decorator + Composite + Singleton

import java.io.*;public class DebuggerToStream implements Debugger {

PrintStream outStrm;public DebuggerToStream(PrintStream strm) {

outStrm = strm;}public DebuggerToStream(OutputStream strm) {

this( new PrintStream(strm) ); }

public void display(String message) {outStrm.println(message);

}

}

public class DebuggerToScreen extends DebuggerToStream {public DebuggerToScreen() {

super(System.out);}

}

public class DebuggerToFile extends DebuggerToStream {public DebuggerToFile(String nameFile)

throws java.io.FileNotFoundException {

super( new FileOutputStream (nameFile) );

}}

اىزحس ثبسزخذاDebuggerToStream

دغ اىند اىشزشك اىـDebuggerToScreen اىـ

DebuggerToFile

حdisplay() حذ

Page 17: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 17

Example of Debugger (5/12) :

Decorator + Composite + Singleton

public class DebuggerInWindow extends javax.swing.JFrame implements Debugger {protected javax.swing.JTextArea zoneDisplay;public DebuggerInWindow() {

super(“Debugger Window");super.setSize(400, 300);zoneDisplay = new javax.swing.JTextArea(40, 20);zoneDisplay.setEditable(false);Container contentPane = super.getContentPane();contentPane.setLayout(new java.awt.BorderLayout());contentPane.add(BorderLayout.CENTER,

new JScrollPane(zoneDisplay));super.show();

}

public void Display(String message){

zoneDisplay.append(message + "\n");}

}

Page 18: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 18

Example (6/12) :

Decorator + Composite + Singleton

public class SolutionWithDebugger {public static void main(String[] args) throws Exception {

main("debugger to screen", new DebuggerToScreen());main("debugger to file", new debuggerToFile("dbg.txt"));main("debugger in window", new DebuggerInWindow());main("without debugger", new WithoutDebugger());

}public static void main(String title, Debugger dbg) {

S.o.p(« Execution with " + title + ".");main(dbg);

}public static void main(dbg) {

dbg.display("Begin of program.");dbg.display("Begin of For.");for(int i=0; i<10; i++) {

dbg.display("Begin of step i=" + i);// ...dbg.display("End of step i=" + i);

}dbg.display("End of For");//....dbg.display("End of program.");

}}

اىضاد: نب رغش ع

اىزقح ثسىخ

اىسئبد: دت قو اىقح

ض مو اىجشبح

اىحو: اسزخذا اىرج

Singleton

Page 19: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 19

Example of debugger (7/12) :

Decorator + Composite + Singletonpublic class SolutionWithDebugger {public static void main(String[] args) throws Exception {S.o.p("Execution without debugger.");main();main("To Screen", new DebuggeToScreen());main("To File", new DebuggerToFile("dbg.txt"));main("In Window", new DebuggerInWindow());main("Withut Debugger", new WthoutDebugger());

}

public static void main(String title, Debugger dbg){S.o.p("Executin with Debugger " + title + ".");SingletonDebugger.setInstance( dbg ); main();}

public static void main() {SingletonDebugger.display("Begin of program");SingletonDebugger.display("Begin of for");for(int i=0; i<10; i++) {

SingletonDebugger.display("Begin of step i=" + i);// ...SingletonDebugger.display("End of step i=" + i);

}//...

}}

public abstract class SingletonDeboggeur {protected static Debugger instance = null;public static Debugger getInstance(){

if(instance == null)instance = new WithoutDebugger();

return instance;}public static void setInstance(Debugger dbg) {

instance = dbg;}public static void display(String message) {

getInstance().display(message);}

}

نب رغش ع اىزقح ثشنو دبن

ثذ رغش ىيجشبح اىز سزخذ اىقح

Page 20: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 20

Example of debugger (7/12) :

Decorator + Composite + Singleton

public class DebuggerToScreenWithDate

extends DebuggerToScreen {

public void display(String message) {

super.dsplay( "[" + new java.util.Date() + "]: " + message );

}

}

ىفشض أب شذ إضبفخ اىزبسخ إه سسبئواىزقح

ىن سحزبج إى صف خذذ ىإلظبس ف بفزح آخش ىإلظبس ػي اىشبشخ آخش إلظبس ض

...يف

public class DebuggerInWindowWithDate

extends DebuggerInWindow{

public void display(String message) {

super.dsplay( "[" + new java.util.Date() + "]: " + message );

}

}

Page 21: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 21

Example of debugger (8/12) :

Decorator + Composite + Singleton

public abstract class DecoratorDebugger implements

Debugger {

protected Debugger dbgr;

public DecoratorDebugger(Debugger d) {

this.dbgr = d;

}

public void display(String message) {

dbgr.display ( decor(message) );

}

protected abstract String decor(String message);

}

ىفشض أب شذ إضبفخ اىزبسخ إه سسبئواىزقح

سسزخذ اىرج اىزصDecorator اىز سح ثزغش سيك غشض فشد د إشبء صفف شزقخ صف زا اىغشض

سنقوم بإنشاء صف لزخرفة األغراض

Debugger

Display(msg)

DecoratorDebugger

DecoratorDebugger()

Display(msg)

Abstract Decor(msg)

Page 22: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 22

Example of debugger (9/12) :

Decorator + Composite + Singleton

public class DebuggerDecoredWithDate

extends DecoratorDebugger {

public DebuggerDecoredWithDate (Debugger d){

super(d);

}

protected String decor(String message) {

return "[" + new java.util.Date() + "] : " +

message;

}

}

public class DebuggerWithoutDecoration

extends DecoratorDebugger {

public DebuggerDecoredWithDate (Debugger d){

super(d);

}

protected String decor(String message) {

return message;

}

}

Debugger

Display(msg)

DecoratorDebugger

DecoratorDebugger()

Display(msg)

Abstract Decor(msg)

DebuggerDecor

edWithDate

Decor(msg)

DebuggerWitho

utDecoration

Decor(msg)

Page 23: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 23

Example of debugger (10/12) :

Decorator + Composite + Singleton

public class SolutionWithDecoration {

public static void main(String[] args) throws Exception

{

Debugger toScreen = new DebuggerToScreen();

Debugger toFile = new DebuggerToFile("dbg.txt");

Debugger inWindow = new DebuggerInWindow();

SolutionWithDebogger.main("to screen with decoration",

new DebuggerDecoredWithDate(toScreen) );

SolutionWithDebogger.main("to file with decoration",

new DebuggerDecoredWithDate(toFile) );

SolutionWithDebogger.main(« in window with decoration",

new DebuggerDecoredWithDate(inWindow) );

}

}

نب اسزخذا اىـDecorator ثأسية آخش

SingletonDebugger.setInstance( new DebuggerDecoredWithDate(new

DebuggerInWindow() ) );

SolutionWithDebugger.main();

هل تتذكرون شيئا مشابها بالـجافا؟

Page 24: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 24

Example of debugger (11/12) :

Decorator + Composite + Singleton

public interface Decoration {

public String decor(String message);

}

رحس ىيحو اىسبثق خاله ػضه سيك.اىضخشفخ ف اخخ فصيخ

public class WithoutDecoration

implements Decoration {

public String decor(String message){

return message;

}

}

public class DecorationWithDate

implements Decoration {

public String decor(String message){

return "[" + new java.util.Date() + "] : " + message;

}

}

public class CompositeDebugger extends DecoratorDebugger {

protected Decoration decoration;

public CompositeDebugger(Debugger dbg,

Decoration dec){

super(dbg);

this.decoration = dec;

}

protected String decor(String message) {

return decoration.decor(message);

}

public void setDecoration(Decoration dec) {

this.decoration = dec;

}

}

Page 25: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 25

Example of debugger (12/12) :

Decorator + Composite + Singleton

اىضاد: نب إضبفخ رفزاد

Debuggerخذذح ىيـ نب إضبفخ رفزاد

خذذح ىيـ Decoration

نب ردغ االث

ال حبخخ ىزؼذو اىصففاىخدح سجقب

دت أ سؼ ثحيىباىغشضخ اىزخ أ رن

ExtensibleReusablemaintenable

public class SolutionByComposition

{

public static void main(String[] args) {

Debugger toScreen = new DebuggerToScreen();

Debugger toFile = new DebuggerToFile("dbg.txt");

Debugger inWindow = new DebuggerInWindow();

Decoration NoDecoration = new WithoutDecoration();

Decoration withDate = new DecorationWithDate();

main("to screen without decoration", toScreen, NoDecoration);

main(« in Window without decoration", inWindow, NoDecoration);

main("to screen with decoration", toScreen, withDate);

main("to file with decoration", toFile, withDate);

main("in window with decoration", inWindow, withDate);

}

public static void main(String title, Debugger dbg,

Decoration dec) {

SolutionWithDebugger( title, new CompisteDebugger(dbg, dec) );

}

}

Page 26: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 26

Structural Design Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.

Page 27: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 27

Proxy (1)

Provide a surrogate or placeholder for another object to control access to it.

Page 28: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 28

Proxy (2)

Applicability :

A remote proxy provides a local representative for an object in a different address space.

A virtual proxy creates expensive objects on demand.

A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights.

A smart reference is a replacement for a pointer that performs additional actions when an object is accessed:

counting the number of references to the real object>>> free this object when there are no more refereces

loading a persistent object into memory when it's first referenced.

checking that the real object is locked before it's accessed to ensure that no other object can change it.

Page 29: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 29

Proxy (3)

Structure

Page 30: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 30

Proxy (4) : remote proxy

Page 31: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 31

Proxy (5) : Stub & Skeleton

public class example_client {

public static void main(String[] args) {

Example ex = new Example();

S.o.p(ex.add(5,3))

}

}

public class example {

public int add(int a, int b) {

ترميز الوسائط //

// استدعاء اإلجرائية من المخدم و انتظار النتيجة

قراءة النتيجة //

}

}

public class example {

public int add(int a, int b) {

return a +b

}

}

public class example_server {

public static void main(String[] args) {

// انتظار طلب من الزبون .

فك ترميز الوسائط //

// استدعاء اإلجرائية المطلوبة

ترميز النتيجة و إرسالها //

}

}Stub Skeleton

Page 32: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

Java & TCP

Creation Socket

Port = x

WelcomSocket = ServerSocket(x)

انتظار لطلبات اتصال

ConnectionSocket = WelcomSocket.accept()

قراءة طلب من

ConnectionSocket

كتابة اإلجابة على

ConnectionSocket

إغالق الـ

ConnectionSocket

قراءة اإلجابة من

ClientSocket

إرسال طلب على

ClientSocket

إغالق الـ

ClientSocket

Creation Socket

Port = x

IP = y

ClientSocket = Socket(x, y)

ServerClient

JPU (ALJAZEERAباسم قصيبة. د32PRIVATE UNIVERSITY)

Page 33: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

TCP Socket

@IP = "M2"

Port = 5040

@IP = "M2"

Port = 5040

@IP = "M1"

Port = 6070

@IP = "M1"

Port = 6070

Remote

Local

Remote

Local

Socket A on M1 Socket B on M2

Out 2

Out 1 In 2

In 1

A.getInetAddress() = B.getLocalInetAddress()

A.getPort() = B.getLocalPort()

A.getLocalInetAddress() = B.getInetAddress()

A.getLocalPort() = B.getPort()

JPU (ALJAZEERAباسم قصيبة. د33PRIVATE UNIVERSITY)

Page 34: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JAVA – Sum TCP Clientimport java.io.*;import java.net.*;public class sumClient {

public static void main(String[] args)throws Exception {BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));try {

InetAddress lclHost = InetAddress.getLocalHost();Socket clientSocket = new Socket(lclHost, 6789);

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());

String nb1 = inFromUser.readLine();String nb2 = inFromUser.readLine();

int n1 = (new Integer(nb1)).intValue();int n2 = (new Integer(nb2)).intValue();

outToServer.writeInt(n1);outToServer.writeInt(n2);

int sum = inFromServer.readInt();

System.out.println("From Server : " + sum);clientSocket.close();

}catch(Exception e) {e.printStackTrace();}

}}

JPU (ALJAZEERAباسم قصيبة. د34PRIVATE UNIVERSITY)

Page 35: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JAVA – Sum TCP Serverimport java.io.*;import java.net.*;public class sumServer {

public static void main(String[] args) throws Exception {

ServerSocket welcomSocket = new ServerSocket(6789);while(true){

System.out.println("Server wait a connection ....");Socket connectionSocket = welcomSocket.accept();

DataInputStream inFromClient = new DataInputStream(connectionSocket.getInputStream());DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

int n1 = inFromClient.readInt();int n2 = inFromClient.readInt();

int sum = n1 + n2;System.out.println(sum);

outToClient.writeInt(sum);}

}}

JPU (ALJAZEERAباسم قصيبة. د35PRIVATE UNIVERSITY)

Page 36: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

Proxy : JavaRMI

Ex : Remote interface + Impl Object

import java.rmi.*;

public interface Addition extends Remote

{

public int add(int x, int y) throws RemoteException;

}

باسم قصيبة. د36

import java.rmi..*;

public class AdditionImpl implements Addition

{

public int add (int x, int y) throws RemoteException

{

return x + y ;

}

}

JPU (ALJAZEERA PRIVATE UNIVERSITY)

Page 37: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

Proxy : JavaRMI

Ex : Server

//deployment of servants

import java.rmi.*;

import java.rmi.server.*;

public class AdditionServer{

public static void main(String[] args){

try{

Addition a = new AdditionImpl();

UnicastRemoteObject.exportObject(a);

Naming.rebind("/Firstpro", a);

System.out.println("First remote program ……”);

System.out.println("main thread finished”);

}

catch(Exception ex) {ex.printStackTrace)(;}

}

}

JPU (ALJAZEERAباسم قصيبة. د37PRIVATE UNIVERSITY)

Page 38: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

Proxy : JavaRMI

Ex : Client

import java.rmi.*;

public class AdditionClient{

public static void main(String[] args) throws Exception {

Addition a = (Addition) Naming.lookup("/Firstpro”);

System.out.println(a.add(5, 3));

}

}

باسم قصيبة. د38

RMI

Server

RMI

ClientStub

1

bind

2

look up

3

5

Argument

marshaling

8

result

Local machine

/ clientRemote machine

/ server

ObjectServer

Skeleton

Registry

0

export

4

Method

call

7

return

9

return

JPU (ALJAZEERA PRIVATE UNIVERSITY)

Page 39: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 39

Structural Design Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.

Page 40: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 40

Adapter (1)

Convert the interface of a class into another interface clients expect.

Adapter lets classes work together that couldn't otherwise because of

incompatible interfaces.

Page 41: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 41

Adapter (2)

Class Adapter pattern

Object Adapter pattern

Page 42: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 42

Adapter (3)

Example :

To use when :

a class exists, but its interface does not match the one you need.

you need to use several existing subclasses, but it's impractical to adapt

their interface by subclassing every one. An object adapter can adapt the

interface of its parent class.

Page 43: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 43

Structural Design Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.

Page 44: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 44

Bridge (1)

Decouple an abstraction from its implementation so that the two can vary independently

problem :

Page 45: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 45

Bridge (2)

Solution with the Bidge pattern :

Page 46: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 46

Bridge (3)

Structure :

To use when : to avoid a permanent binding between an abstraction and its

implementation. (example, the implementation must be selected or switched at run-time).

both the abstractions and their implementations are independently extensible by subclassing.

changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.

Page 47: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 47

Bridge (4)

Example :

BridgeImpl

addLine (String s)

Bridge

addData (List l)

Forall x in l

imp.addLine (x)

imp

List View

AddLine( String s)

{

Jlist.add )…..(

}

TableView

AddLine( String s)

{

JTable.add )…..(

}

SortedBridge

addData (List l)

{

l = Sort(l);

super.addData(l)

}

ListBridge

Page 48: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 48

Structural Design Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.

Page 49: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 49

Flyweight (1)

Use sharing to support large numbers of fine-grained objects efficiently.

Page 50: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 50

Flyweight (2)

Page 51: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 51

Flyweight (3)

Structure

Page 52: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 52

Flyweight (4)

Applicability : An application uses a large number of objects.

Storage costs are high because of the sheer quantity of objects.

Most object state can be made extrinsic.

Many groups of objects may be replaced by relatively few shared objects

once extrinsic state is removed.

The application doesn't depend on object identity.

Page 53: Structural Patterns - jude.edu.syjude.edu.sy/assets/uploads/lectures/structuralPatterns-jz.pdf · Structural Patterns (2) Decorator Attach additional responsibilities to an object

JPU (ALJAZEERA PRIVATE UNIVERSITY)

باسم قصيبة. د 53

Structural Designيخص ػ أذاف اىـ

Patterns

Composite = Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Adapter = Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge = Decouple an abstraction from its implementation so that the two can vary independently.

Decorator = Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade = Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight = Use sharing to support large numbers of fine-grained objects efficiently.

Proxy = Provide a surrogate or placeholder for another object to control access to it.