design patterns – details part 2 gang of four (gof) patterns grasp patterns more sources: chapter...

35
Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing the Logical Architecture with Patterns Craig Larman’s Text: Applying UML and Patterns, Chaps: 16, 17, 22, & 23. WWW, personal notes, and more.

Upload: ann-rice

Post on 12-Jan-2016

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Design Patterns – DetailsPart 2

Gang of Four (GoF) Patterns

GRASP Patterns

MoreSources:

Chapter 6: Using Design Patterns, and

Chapter 30 (parts) Designing the Logical Architecture with Patterns

Craig Larman’s Text: Applying UML and Patterns, Chaps: 16, 17, 22, & 23.

WWW, personal notes, and more.

Page 2: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

General Design Pattern

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 2

Page 3: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 3

1. The Abstraction-Occurrence Pattern

• Context: — Often found in class diagrams that form part of the system

domain model.—Often in a domain model you find a set of related objects

(occurrences).—The members of such a set share common information but also

differ from each other in important ways. (Sports cars ….)• Problem:

—What is the best way to represent such sets of occurrences in a class diagram? Use the commonality, yet represent the differences!

•  Forces: —You want to represent the members of each set of occurrences

without duplicating the common information. - Cannot have this!

—Want to maximize the flexibility of the system too.

Page 4: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 4

Abstraction-Occurrence

• Solution:

TVSeries

seriesNameproducer

Episode

numbertitlestorySynopsis

******

«Occurrence»«Abstraction» ******

Title

nameauthor

LibraryItem

barCodeNumber******

isbnpublicationDatelibOfCongress

Note: create an abstraction containing common data to all occurrences.This is the “abstraction”. Then create the “occurrence” class that represents instances (occurrences) of the abstraction. Realtionship is 1:*ForeignSportsCar { CarMake; CountryofOrigin…} Auto { Model, Style, Cost..}Note (as we shall see) this is not inheritance.

Remember (Java): anInterface can have NO implementations; may at most have constants;Abstract Class has at least one abstract method; can have declarations.

Page 5: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 5

Abstraction-Occurrence Antipatterns:

nameauthor

LibraryItem

barCodeNumber

isbnpublicationDatelibOfCongress

Title

nameauthor

LibraryItem

barCodeNumber

isbnpublicationDatelibOfCongress

nameauthor

LibraryItem

barCodeNumber

isbnpublicationDatelibOfCongress

GulliversTravels MobyDick

Single class: Bad because info would have to be duplicated in each occurrence – and same info would be in each occurrence!

Here, separate subclass for each title.All other information would have to be duplicated in each instance.Also, want to be able to add new books without programming new classes!

Problem here is making the abstract class a super class of the occurrence.Attributes would beinherited, of course, butdata would be lost! We’d have to fill in name, author … for each occurrence!

Page 6: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Gang of Four (GoF) Patterns

Singleton

Observer

Delegation

Adaptor

Façade

Proxy

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 6

Page 7: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 7

2. The Singleton Pattern (Gang of Four)

• Context: —It is very common to find classes for which only one

instance should exist (singleton) - Examples: a Main Window; Company or University class.

• Problem:

—How do you ensure that it is never possible to create more than one instance of a singleton class?

• Forces:

—The use of a public constructor cannot guarantee that no more than one instance will be created.

—The singleton instance must also be accessible to all classes that require it

Page 8: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 8

Singleton

• Solution:

Company

theCompany

Company «private»getInstance

if (theCompany==null) theCompany= new Company();

return theCompany;

«Singleton»

theInstance

getInstanceHave a private class variable, possibly called, ‘theInstance.’ This stores the instance.

Then have a public class method(static method) possibly called,‘getInstance.’

First time method is called, it creates Here, Company class may embody several a single instance and stores it in important characteristics of the Company theInstance.. Subsequent calls simply (operations and attributes). return theInstance.

The public class method getInstance() makesA private Constructor, which ensures this instance globally accessible. no other class will be able to create an instance of the singleton class is Note: effectively, the Singleton instance is needed. effectively a global variable. Minimize these.

Page 9: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Controversy

There is criticism of the use of the singleton pattern, as some consider it an anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application

The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.

Façade objects are often Singletons because only one Façade object is required.

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 9

Page 10: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 10

3. The Observer Pattern (Gang of Four)

• Second in the gang-of-four patterns (Singleton was the first)• This is another VERY popular one.• Context:

—When you have a two-way association is created between two classes, the code for the classes becomes inseparable.

—If you want to reuse one class, then you also have to reuse the other. There is a dependency.

• Problem: —How do you reduce the interconnection between classes,

especially between classes that belong to different modules or subsystems?

• Forces: —You want to maximize the flexibility of the system to the

greatest extent possible

Page 11: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 11

Observer• Example:

WeatherViewer

* ******

Observers are notified when a new prediction is readyForecaster

Observable

«ConcreteObservable» «ConcreteObserver»

«Observable»

addObservernotifyObservers

«interface»«Observer»

update

* ****** «interface»Observer

Java has an Observer interface and an Observable class. This is a specificimplementation of this pattern.

Consider: a ‘forecast’ requires a lot ofcomputations. Once done, it ‘notifies’ all interested instances.

Forecaster is thus an observable object.

One observer object might be an interface object responsible for displaying weather forecast; another might be dependent on weather information to plan a schedule..

Observer pattern in widely used to structure software cleanly into relatively independent modules. It is the basis of the MVC architecture.

Just a class…

Page 12: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 12

Observer• Solution:

So, what do we do? We create an abstract class we will call <<Observable>> that maintains a collection of <<Observer>> instances.

<<Observable>> class is very simple; it merely has a mechanism to add and remove observers as well as a method, notifyObservers, that sends an update message to each <<Observer>>.

Any application class can declare itself to be a subclass of the <<Observable>> class. In Java, we call these ‘listeners.’

So, the listener (concrete observable) implements addObserver and notifyObservers.

* ******

«ConcreteObservable» «ConcreteObserver»

«Observable»

addObservernotifyObservers

«interface»«Observer»

update

*****

<<abstract>>

<<abstract>>

Page 13: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Observer

The Observer Pattern (aka Dependents, Publish/Subscribe) is a software design pattern in which an object, called the subject (Observable here), maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods, update in the previous slide.

Mainly used to implement distributed event handling systems.

Observer is also a key part in the familiar MVC architectural pattern.

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 13

Page 14: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Observer

The essence of the Observer Pattern is to “define a one to many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 14

<<observable>> earlier

Page 15: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 15

4. The Delegation Pattern

• Context:

—You are designing a method in a class

—You realize that another class has a method which provides the required service

—Inheritance is not appropriate (e.g. because the ‘isa’ rule does not apply

• Problem:

—How can you most effectively make use of a method that already exists in the other class?

• Forces:

—You want to minimize development cost by reusing methods; also reduce coupling between classes. Too, methods should be near the data, and the existing class with the method might be the more appropriate place for the existing method. So, …

Page 16: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 16

Delegation

• Solution:

«Delegate»«Delegator»delegatingMethod() {

delegate.method();

} delegatingMethod method

Create a method in a Delegator class that only calls a method in a neighboring Delegate class.

In this way, we are reusing the method for which Delegate has responsibility.

By neighboring class, we mean that the Delegate has an association with the Delegator class.

Page 17: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 17

Delegation• Solution:

LinkedList

addFirstaddLastaddAfterremoveFirstremoveLastdeleteisEmpty

Stack

pushpopisEmpty

push() { list.addFirst(); }

Here we can see that Stack operations push, pop, and isEmpty can readily use existing methods from Linked List class – addFirst, addLast, and isEmpty.

Thus, we have the above relationship.

Page 18: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 18

Delegation (continued)

Normally, the association already exists, and association need only be unidirectional. We may sometimes need to create a new association, if the additional complexity doesn’t increase overall complexity too much.

Kind of a ‘selective inheritance.’

Page 19: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 19

Delegation

Antipatterns – This is not good:

• Overuse generalization and inherit the method that is to be reused instead of creating a single method in the «Delegator» that does nothing other than call a method in the «Delegate

• Access non-neighboring classes

Page 20: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 20

5. The Adapter Pattern

• Context: —You are building an inheritance hierarchy and want to

incorporate it into an existing class. —The reused class is also often already part of its own

inheritance hierarchy.• Problem:

—How to obtain the power of polymorphism when reusing a class whose methods

- have the same function- but not the same signature

as the other methods in the hierarchy?• Forces:

—You do not have access to multiple inheritance or you do not want to use it.

Page 21: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 21

Adapter• Solution:

«Adaptee»

adaptedMethod

«Superclass»

polymorphicMethod

«Adapter»

polymorphicMethod()

return adaptee.adaptedMethod();

{

}

We don’t want to directly incorporate the reused class into our inheritance hierarchy.Better: Use an <<Adapter>> class that is connected via association to the reused class. (Adaptee)

The polymorphic methods of <<Adapter>> delegate to methods of <<Adaptee>>, and delegatemethod in <<Adaptee>> may / may not have same name as delegating polymorphic method. Anything else in <<Adapter>> will be unaware that it is indirectly using the facilities of an instance of <<Adaptee>>.

Page 22: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 22

Adapter

Example:

TimsTorus

calcVolume

ThreeDShape

volume

Sphere Torus

volume()

return adaptee.calcVolume();

{

}

We want to create a hierarchy of three-dimensional shapes, and we’d like to use an existing implementation of calcVolume in TimsTorus. (TimsTorus is already in its own hierarchy)We cannot modify the code in TimsTorus because it is being used by others, and thus cannot make it a subclass of ThreeDShape.So, we develop Torus (an <<Adapter>>) such that its instances have a link to the instance of TimsTorus and delegate all operations to TimsTorus.

Adapters are sometimes called Wrappers. Java wrapper classes Integer, Float, Double, etc are adapters for the Java primitive types.

Page 23: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Adapter (Internet)

The adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface.

An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface.

The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small.

There are two types of adapter patterns:

Object Adapter pattern and

Class Adapter pattern.

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 23

Page 24: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Object Adapter Pattern

In this type of adapter pattern, the adapter contains an instance of the class it wraps (Adaptee) so it can call the method, methodB(). In this situation, the adapter makes calls to the instance of the Adaptor via adaptor.methodA(), which invokes adaptee.methodB().

Above is The object adapter pattern expressed in UML. The adapter hides the adaptee's interface from the client.

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 24

Page 25: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Class Adapter Pattern

This type of adapter uses multiple polymorphic interfaces to achieve its goal.

The adapter is created by implementing or inheriting both the interface that is expected and the interface that is pre-existing.

It is typical for the expected interface to be created as a pure interface class, especially in languages such as Java that do not support multiple inheritance.

Adaptor inherits the interface and

implements the interface (see method1()

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 25

Page 26: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 26

6. The Façade Pattern

• Context:

—Often, an application contains several complex packages.

—A programmer working with such packages has to manipulate many different classes

• Problem:

—How do you simplify the view that programmers have of a complex package?

• Forces:

—It is difficult for a programmer to understand and use an entire subsystem

—If several different application classes call methods of the complex package, then any modifications made to the package will necessitate a complete review of all these classes.

Page 27: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 27

Façade Pattern (GofF) For Subsystem Packages:

• Here, the most common pattern of access is Façade, a GoF design pattern.

• We have a public façade object defining the services for the subsystem, and clients collaborate with the façade, not internal subsystem components.

• The façade should not normally expose many low-level operations. Rather, it exposes a small number of high-level operations – the coarse-grained services.

• A façade does not normally do its own work. Rather, it is consolidator or mediator to the underlying subsystem objects, which do the work.

• The façade is a wrapper and single point of access into the ‘rules engine’ of a subsystem.

• Other packages do not see the implementation of the subsystem, as it is hidden behind the façade.

Page 28: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

FaçadeFacade pattern: software engineering design pattern commonly used with OOP.

A facade is an object that provides a simplified interface to a larger body of code, such as a subsystem or a class library.

Below: The façade class abstracts Packages 1,2, and 3 from the rest of the application.

Clients use the façade pattern to access resources from the packages.

They are going to ‘doStuff’ with the objects c1, c2, and c3

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 28

Page 29: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 29

Façade• Another view:

«PackageClass3»

«PackageClass2»

«PackageClass1»

*****

*****

«Facade»

We create a special class called a <<Façade>>, which simplifies the use of the package.The Façade class simply contains a simplified set of public methods.

Result is the creation of a class containing the most often used / needed facilities in the package. Thus other client elements desiring services of this complex package can avail themselves of the Façade class, where it is likely what services they want are simpler to acquire.

Since we are talking about a complex package, other clients that need some of the complexities of the package can access these services as they normally would – via the public interfaces of these other classes.

Page 30: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 30

Façade• Example: ****** RegularFlight

******Person

Airline

findFlightmakeBookingdeleteBooking

Airline reservation systems have many classes and methods.

Some design elements, like subsystems, may need to interact with the airline system but don’t want to be exposed to any changes that might be made to it (via dependencies).

So, we can define and Airline class to be a <<Façade>> that contains methods (access) to the most important query and booking operations in other classes in the airline system.

Thus any dependency arising from this relation is only on the Façade class.

Here, above, via the Airline façade class, we have access to two other classes from other likely complex packages

<<façade>>

Page 31: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 31

7. The Proxy Pattern

• Context: —Often, it is time-consuming and complicated to create instances of

a class (heavyweight classes). —There is a time delay and a complex mechanism involved in

creating the object in memory. Large classes must be loaded from a database to support usage.

• Problem: —How to reduce the need to create instances of a heavyweight

class? —Other objects may need to refer to or use instances of heavyweight

classes.—Many domain classes are heavyweight classes; also common

for the collection classes used to implement associations (like ArrayList or Vector) to be heavyweight classes too.

—So, how can we reduce the need to create instances of heavyweight classes and/or to load large numbers of them from a database or server when not all of then will be needed?

Page 32: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 32

Proxy• Forces:

—We want all the objects in a domain model to be available for programs to use when they execute a system’s various responsibilities.

—It is also important for many objects to persist from run to run of the same program and it is impractical for all the objects to be loaded into memory when a program starts.

—It would be much better to do the programming as if all objects were already loaded into memory.

- Some programmers concerned with loading and storing the objects

- Some programmers concerned with implementing the responsibilities of the domain model.

• A proxy, in its most general form, is a class functioning as an interface to something else.

• The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

Page 33: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

Proxy

In situations where multiple copies of a complex object must exist, the proxy pattern can be adapted to incorporate the lightweight pattern in order to reduce the application's memory footprint.

Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to a single original complex object.

Any operations performed on the proxies are forwarded to the original object.

Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 33

Page 34: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 34

Proxy

• Solution:«interface»«ClassIF»

* ******«Client» «HeavyWeight»«Proxy»

Create a simpler version of the heavyweight class, which we call a Proxy, which has the same interface as the heavyweight class so programmers can declare variables without caring about whether the Proxy or its Heavyweight version will be put in the variable.

The Proxy object is really only a placeholder, and the operations in the Proxy delegate the operation to the HeavyWeight.

If/when needed, the Proxy can obtain the real heavyweight object. Further, the proxy only needs to obtain the heavyweight one time and thus make it available in memory to others who use the proxy.

Some proxies may have implementations of a limited number of operations that can be performed without the effort of loading the Heavyweight object.

Page 35: Design Patterns – Details Part 2 Gang of Four (GoF) Patterns GRASP Patterns More Sources: Chapter 6: Using Design Patterns, and Chapter 30 (parts) Designing

© Lethbridge/Laganière 2001 Chapter 6: Using design patterns 35

Proxy - Example

Example:«interface»

ListIF

The list elements will be loaded into local memory only when needed.

ListProxy PersistentList

«interface»Student

PersistentStudentStudentProxyHere we have a variable that is to contain a List. This variable would, however, actually contain a ListProxy, since it would be expensive to load an entire list of objects into memory, and the list might not actually be needed. However, as soon as an operation accesses the list, the ListProxy might at that point create an instance of PersistentList.

On the other hand, the ListProxy might be able to answer certain queries, such as the number of elements in the list, without going to the effort of loading the PersistentList.

Imagine that the PersistentList is actually a list of students. These objects might also be proxies – in this case, instances of StudentProxy. Again, instances of PersistentStudent would only be loaded when necessary.