+ All Categories
Home > Documents > 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control...

1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control...

Date post: 21-Dec-2015
Category:
View: 217 times
Download: 4 times
Share this document with a friend
42
1 Proxy Design Pattern Proxy Design Pattern • Intent Provide a surrogate or placeholder for another object to control access to it. An example Image handling in a web browser When a high-resolution image is embedded in an HTML file, Only a bounding box (fake/virtual image) is drawn first, and coordinated with surrounding text. » because most users are not patient enough to keep watching blank browser windows until both text and image are downloaded. Whenever the image is downloaded, the bounding box is replaced with the real image. The image is gradually drawn from a lower to higher resolutions.
Transcript
Page 1: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

1

Proxy Design PatternProxy Design Pattern• Intent

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

• An example– Image handling in a web browser

• When a high-resolution image is embedded in an HTML file,– Only a bounding box (fake/virtual image) is drawn first, and coordinated with

surrounding text. » because most users are not patient enough to keep watching blank browser

windows until both text and image are downloaded.

– Whenever the image is downloaded, the bounding box is replaced with the real image.

– The image is gradually drawn from a lower to higher resolutions.

Page 2: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

2

<<interface>>Image

ImageProxy ImageImpl

draw()getExtent()

ImageProxy()draw()

drawBBox()getExtent()

fetchImage()

image

1

Browser

extent

draw()getExtent()

extent

Page 3: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

3

<<interface>>Image

ImageProxy ImageImpl

draw()getExtent()

ImageProxy()draw()

drawBBox()getExtent()

fetchImage()

image

1

Browser

extent

draw()getExtent()

extent

Obtained from a HTML file(width=“100” height=“50”)Or, the default extent used.

if( image == null){ drawBBox( getExtent() );} else { image.draw(); }

if( image == null){ return extent;} else { image.getExtent(); }

Image img = new ImageProxy(…);img.draw();

Create a thread, and using the thread, start downloading a target image from a remoteweb site. Once it is done, instantiate Image and call draw()

fetchImage(…);

Page 4: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

4

Iterator Design PatternIterator Design Pattern

• Intent– Provides a uniform way to access/traverse the

elements of an aggregate object (e.g., collection object) sequentially without exposing its underlying representation (data structure).

• A “uniform” access/traversal way for different types of aggregate objects

– Abstract access mechanisms for collection types, and encapsulate that in the iterator.

• Separate collections from access mechanisms (i.e., how to access collections)

• Hide access mechanisms from collection users.

Page 5: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

5

An Example in Java An Example in Java • Collection collection = ….;

java.util.Iterator iterator = collection.iterator();while ( iterator.hasNext() ) {

Object o = iterator.next();System.out.print( o );

}

– Different access mechanisms must be implemented for different collection types (e.g., list, bag, tree and table).

– Collection users can use the the same/uniform way to access different collection types.

• There are so many collection types in Java.

Page 6: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

6

Class StructureClass StructureClient (or user)

《 interface》Iterator

《 interface》Collection

LinkedList VectorListIterator VectorIterator

<-- create use -->

Users knows thesetwo interfaces.

Users do not haveto know this level.This level is hiddenfrom users.

hasNextnext()

iterator()add()remove()…

Page 7: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

7

What’s Hidden from Users? What’s Hidden from Users? Client (or user)

《 interface》Iterator

《 interface》Collection

LinkedList VectorListIterator VectorIterator

hasNextnext()

iterator()add()remove()…

iterator()…

return new VectorIterator(this);

VectorIterator(Vector vec)hasNext()

-vector

1

this.vector = vec;this.index = 0;this.size = vec.size();

if( size == index ) return false;return true;return vec.get( index );

index: intSize: int

Page 8: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

8

Key PointsKey Points• User's point view

– java.util.Iterator iterator = collection.iterator();– Iterator instances always implement the Iterator interface.

– No need to know what specific implementation class is returned/used.

• In fact, VectorIterator does not exist in Java API. • The API documentation provides no information about

implementation classes.• Simple contract: get an interator with iterator() and call next() on that

– No need to change user code when implementation classes are changed.

– Important Principle: Program to an interface, not an implementation

Page 9: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

9

• Collection developer’s point view – No need to change existing implementation classes (collection

access mechanisms) when a new collection type is introduced.

– Iterator and its implementation classes form the Strategy pattern.

– iterator() is a factory method.

Page 10: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

10

Factory MethodFactory Method• a.k.a.

– Virtual constructor• A normal method that creates instances.

• Intent– Let a class (or interface) defer instantiation of subclasses (or

implementation classes). • At compile time, users do not need to determine and write what

subclasses (impl classes) to instantiate. The decision can be deferred to runtime.

– Separate class instantiation from users, and encapsulate that in a factory method.

• Hide instantiation from users of subclasses (impl classes)

Page 11: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

11

Client (or user)

《 interface》Iterator

《 interface》Collection

LinkedList VectorListIterator VectorIterator

hasNextnext()

iterator()iterator()add()remove()…

iterator()…

return new VectorIterator(this); return new VectorIterator(this);

VectorIterator(Vector vec)hasNext()

-vector

1

this.vector = vec;this.index = 0;this.size = vec.size();

if( size == index ) return false;return vec.get( index );

index: int

An Example: IteratorAn Example: Iterator

Page 12: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

12

Another Example: ProxyAnother Example: Proxy

Page 13: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

13

Recap: Proxy Design PatternRecap: Proxy Design Pattern

<<interface>>Image

ImageProxy ImageImpl

draw()getExtent()

ImageProxy()draw()

drawBBox()getExtent()

fetchImage()

image

1

Browser

extent

draw()getExtent()

extent

Obtained from a HTML file(width=“100” height=“50”)Or, the default extent used.

if( image == null){ drawBBox( getExtent() );} else { image.draw(); }

if( image == null){ return extent;} else { image.getExtent(); }

Image img = new ImageProxy(…);img.draw();

Create a thread, and using the thread, start downloading a target image from a remoteweb site. Once it is done, instantiate Image and call draw()

fetchImage(…);

Page 14: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

14

<<interface>>Image

<<interface>>ImageProxy

<<interface>>AbstractImageImpl

draw()getExtent()

ImageProxy()draw()

drawBBox()getExtent()

fetchImage()

image

1

Browser

draw()getExtent()

Factory Method in ProxyFactory Method in Proxy

JpegImgProxy SvgImgProxy

JpegImage SvgImage

Page 15: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

15

List<Image> imgList = htmlFile.getImages();for each img of imgList { img.draw(); }

<<interface>>Image

<<interface>>ImageProxy

<<interface>>AbstractImageImpl

draw()getExtent()

ImageProxy()draw()

drawBBox()getExtent()

fetchImage()

image

1

Browser

draw()getExtent()

JpegImgProxy SvgImgProxy

JpegImage SvgImage

Factory method forimpl classes of AbstractImageImpl

Page 16: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

16

Other ExamplesOther Examples

• Object pool– Connection pool– Thread pool

• Singleton

Page 17: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

17

Singleton Design PatternSingleton Design Pattern

• Guarantee that a class has only one instance.

– public class Singleton{private static Singleton instance = null;private Singleton(){}public static synchronized Singleton getInstance() {

if( instance==null){instance = new Singleton(); }

return instance; }}

Page 18: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

18

ExamplesExamples

• Object pools

• Cache

Page 19: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

19

Colleague

Colleague1 Colleague2

Mediatormediator

ConcreteMediator

Mediator Design PatternMediator Design Pattern• Intent

– Define a class that encapsulates how a set of objects interact.– Control the interaction in a centralized (single) place– Promote loose-coupling among objects

1

Page 20: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

20

OrderProcParticipant

Faculty

Mediator mediator

OrderProcMediator

1initOrderProc(f:OrderProcParticipant)

initOrderProc(f:OrderProcParticipant)getStatus(): OrderProcStatus

Order Account

orderInitiator order account

Page 21: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

21

OrderProcParticipant

Faculty

Mediator mediator

OrderProcMediator

1initOrderProc(f:OrderProcParticipant)

initOrderProc(f:OrderProcParticipant, o: Order, a: Accout)getStatus(): OrderProcStatus

Order Account

orderInitiator order account

If( f’s type is not Faculty) throw an exception;orderInitiator = f;order = o;account = a;f is the owner of a? order.getItem().getCost() < account.balance()?status = OrderProcStatus.AUTHORIZED

returns status;

What if a more complicatedbusiness Process is implemented?Purchaser, supervisor, auditor, etc. etc.

Page 22: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

22

IMParticipant

PremiumUser RegularUser

Mediatormediator

ConfCallMediator

1

showMsg(msg: String)register(p: IMParticipant)

sendMsg(msg: String)

showAd(ad: Ad)

pUsers

rUsers

register(p: IMParticipant)sendMsg(msg: String)

Page 23: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

23

IMParticipant

PremiumUser RegularUser

Mediatormediator

ConfCallMediator

1

showMsg(msg: String)register(p: IMParticipant)

sendMsg(msg: String)

showAd(ad: Ad)

pUsers

rUsers

register(p: IMParticipant)sendMsg(msg: String)

if( p’s type is PremiumUser ){ pUsers.add(p); p.log();}if( p’s type is RegularUser) rUser.add(p);

for each of pUsers { each.showMsg( msg );}for each of rUsers { each.showAd( new Ad(…) ); each.showMsg( msg );}

The Strategy pattern used.What if new user types are added?

Page 24: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

24

Code Reuse in OOPCode Reuse in OOP

• Three categories of code reuse– Inherit an existing class

• SSLServerSocket extends ServerSocket

– Instantiate an existing class• new Thread(new YourOwnRunnable() )

– Combine instances at runtime• Decorator design pattern

Page 25: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

25

When is Instance Combination Useful?When is Instance Combination Useful?• class VisualString{

private String string; public void draw(){ // draw a string on the screen } }

• You want to draw a box around the string.– class BoxedString extends VisualString{

public void draw(){ // redefine how to draw a string } }

• You want to draw a string in color.– Class ColoredString extends VisualString{

public void draw(){ // redefine how to draw a string } }

• What if you want to draw a box around a colored string? • What if you want to draw a box around an icon?

Page 26: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

26

• class Customer{ public double getAnnualFee(){ … } }

• class DomesticCustomer extends Customer{ public double getAnnualFee(){ … } }

• class InternationalCustomer extends Customer{ public double getAnnualFee(){ … } }

• What if you want to set up – domestic/international cooperate, individual and government

customers – VIP discount rate employee discount rate?

• What if you want to change the status of a customer from non-VIP to VIP or domestic to international?

Page 27: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

27

Decorator Design PatternDecorator Design Pattern

• a.k.a. pluggable objects

CustomerCustomerCorporateCorporateDomesticDomestic CustomerCustomerindividualindividualIntlIntlVIPVIP

Page 28: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

28

Sample Code: Structure of ClassesSample Code: Structure of Classes<<interface>><<interface>>

EntityEntity

getAnnualFee()getAnnualFee()

CustomerCustomer

getAnnualFee()getAnnualFee()

EntityDecoratorEntityDecorator{abstract}{abstract}

getAnnualFee()getAnnualFee()

entityentity

DomesticDecoratorDomesticDecorator IntlDecoratorIntlDecorator

getAnnualFee()getAnnualFee()

IndividualDecoratorIndividualDecorator CorporateDecoratorCorporateDecorator

getAnnualFee()getAnnualFee()

VIPDecoratorVIPDecorator

getAnnualFee()getAnnualFee()

GovDecoratorGovDecorator

getAnnualFee()getAnnualFee()

Page 29: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

29

Sample Code: Instance CombinationSample Code: Instance Combination• Customer customer =

new Customer();customer.getAnnualFee(); --> 100.0

• Customer customer = new DomesticDecorator( new CorporateDecorator( new Customer() ) );customer.getAnnualFee(); --> 1000.0

– The kernel + 2 skins (decorators)

CustomerCustomerCorporateCorporateDomesticDomestic

CustomerCustomer

main()main()

getAnnualFee()getAnnualFee()

100100

100*10100*1010001000

10001000

Page 30: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

30

• new InternationalDecorator( new GovernmentDecorator( new Customer() ) );

• new VIPDecorator( new IndividualDecorator( new Customer() ) );

CustomerCustomerGovGovIntlIntl

main()main()

getAnnualFee()getAnnualFee()

100100

100*3100*3300300

300*1.2300*1.2360360

CustomerCustomerIndividualIndividualVIPVIP

main()main()

getAnnualFee()getAnnualFee()

100100

100100

100*0100*000

Page 31: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

31

Java I/O APIJava I/O API• InputStream and OutputStream

– Abstract classes that represent input and output byte streams.

• Reader and Writer– Abstract classes to read and write character streams

• Many filters are defined to tailor specialized input/output streams and readers/writers.

InputStreamInputStream

FiltersFilters

ObjectsObjectsAudioAudioFileFileChars, etc. Chars, etc.

FiltersFilters

ReaderReader

Byte steamByte steam

Char steamChar steamFiltersFilters

WriterWriter

OutputStreamOutputStream

FiltersFilters

Characters Characters Characters Characters ObjectsObjectsAudioAudioFileFileChars, etc. Chars, etc.

Page 32: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

32

InputStreamInputStream• InputStream objects can be decorated

with an arbitrary number of filters.

• InputStream classes– AudioInputStream– FileInputStream– ObjectInputStream– PipedInputStream– …etc.– SocketInputStream (hidden)

FileInputStreamInputStreamInputStream

FiltersFilters

Files Files

InputStreamInputStream{abstract}{abstract}

read()read()close()close()

FilterInputStreamFilterInputStream

read()read()close()close()

filtersfilters

InputStreamInputStreamclassesclasses

inin

AudioInputStream

Audio Audio

ObjectInputStream

Objects Objects

SocketInputStream

Data fromData fromsocket socket

Page 33: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

33

Initialization of InputStreamInitialization of InputStream• InputStream is = new FileInputStream(“foo.txt);

InputStream is = new FileInputStream(System.in);

fis.read();

• Socket socket = new Socket(…);InputStream is = socket.getInputStream();is.read();– System.out.println(socket.getInputStream().toString() );

• java.net.SocketInputStream@10d81b

FileInputStreamInputStreamInputStream

FiltersFilters

Files Files

SocketInputStream

Data fromData fromsocket socket

Page 34: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

34

• Some InputStream objects can be connected with each other.

• InputStream is = new AudioInputStream(new FileInputStream( “audiofile”) );

• InputStream is = new AudioInputStream(socket.getInputSteam() );

• InputStream is = new ObjectInputStream(new FileInputStream( “objectfile”) );

AudioInputStream

Audio Audio

FileInputStream

AudioInputStream

Audio Audio

SocketInputStream

ObjectInputStream

Object Object

FileInputStream

Page 35: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

35

Filters of InputStreamFilters of InputStream• Filters

– BufferedInputStream– CheckedInputStream (java.util.zip)– ZipInputStream (java.util.zip)– GZIPInputStream (java.util.zip)– JarInputStream (java.util.zip)– CipherInputStream (javax.crypto)– DifestInputStream (java.security)– …etc.

• A single InputStream object can be decorated with multiple filters.

InputStreamInputStream{abstract}{abstract}

read()read()close()close()

FilterInputStreamFilterInputStream

read()read()close()close()

filtersfilters

InputStreamInputStreamclassesclasses

inin

FileInputStreamInputStreamInputStream

FiltersFilters

Files Files

AudioInputStream

Audio Audio

ObjectInputStream

Objects Objects

SocketInputStream

Data fromData fromsocket socket

Page 36: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

36

• InputStream is = new Buffered(socket.getInputStream() );

is.read();

• InputStream in =new ZipInputStream (

new FileInputStream(…) );in.read();

• InputStream in = new BufferredInputStream( new ZipInputStream( socket.getInputStream() ));in.read();

Page 37: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

37

OutputStreamOutputStream• OutputStream objects can be decorated

with an arbitrary number of filters.

• OutputStream classes– FileOutputStream– ObjectOutputStream– PipedOutputStream– …etc.– SocketOutputStream (hidden)

OutputStreamOutputStream{abstract}{abstract}

write()write()close()close()

FilterOutputStreamFilterOutputStream

write()write()close()close()

filtersfilters

OutputStreamOutputStreamclassesclasses

FileOutputStreamOutputStreamOutputStream

FiltersFilters

Files Files

ObjectOutputStream

Objects Objects

SocketOutputStream

Data fromData fromsocket socket

outout

Page 38: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

38

Initialization of OutputStreamInitialization of OutputStream• OutputStream os = new FileOutputStream(“foo.txt);

OutputStream os = new FileOutputStream(System.in);

fis.read();

• Socket socket = new Socket(…);OutputStream os = socket.getOutputStream();is.read();– System.out.println(socket.getOutputStream().toString() );

• java.net.SocketOutputStream@11d32c

FileOutputStreamInputStreamInputStream

FiltersFilters

Files Files

SocketOutputStream

Data fromData fromsocket socket

Page 39: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

39

• Some OutputStream objects can be connected with each other.

• OutputStream os = new ObjectOutputStream(new FileOutputStream( “objectfile”) );

ObjectInputStream

Object Object

FileInputStream

Page 40: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

40

Filters of OutputStreamFilters of OutputStream• Filters

– BufferedOutputStream

– PrintStream

– CheckedOutputStream (java.util.zip)

– ZipOutputStream (java.util.zip)

– GZIPOutputStream (java.util.zip)

– JarOutputStream (java.util.zip)

– CipherOutputStream (javax.crypto)

– DifestOutputStream (java.security)

– …etc.

• A single OutputStream object can be decorated with multiple filters.

OutputStreamOutputStream{abstract}{abstract}

write()write()close()close()

FilterOutputStreamFilterOutputStream

write()write()close()close()

filtersfilters

OutputStreamOutputStreamclassesclasses

outout

Page 41: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

41

• OutputStream os =new ZipOutputStream(

new FileOutputStream(…) );os.write();

• OutputStream os =new BufferredOutputStream(

new ZipOutputStream(socket.getOutputStream() ));

os.write();

• OutputStream os =new PrintStream(

socket.getOutputStream() );os.write();

Page 42: 1 Proxy Design Pattern Intent –Provide a surrogate or placeholder for another object to control access to it. An example –Image handling in a web browser.

42

Readers, Writers and Utility ClassesReaders, Writers and Utility Classes

• PrintWriter

• Scanner– A text scanner that can parse primitive types and

strings using regular expressions.

• FileReader– Convenience class for reading character files.

• FileWriter – Convenience class for writing character files.


Recommended