Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… ·...

17
Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden Report No TENTA_TDDB84 Organization Linköping University, Sweden Last Modified 20 October 2009 Modified by Peter Bunus ([email protected]) Tentamen TDDB84 (Design Mönster) Examination TDDB84 (Design Patterns)

Transcript of Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… ·...

Page 1: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Report No TENTA_TDDB84 Organization Linköping University, Sweden Last Modified 20 October 2009 Modified by Peter Bunus ([email protected])

Tentamen TDDB84 (Design Mönster) Examination TDDB84 (Design Patterns)

Page 2: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Table of Contents

Information ................................................................................................................................................... 1 Betygsgränser ............................................................................................................................................... 1 Information ................................................................................................................................................... 2 Grading ......................................................................................................................................................... 2 Task 1: Short Answer – Short Motivation (20 points / 2 points for each question) ..................................... 3 Task 2: Airline Frequent Flyer Program (20 points) .................................................................................... 8 Task 3: Facebook (20 points) ..................................................................................................................... 10 Task 4: Facebook Continued (20 points) .................................................................................................... 13 Task 5: Managing Courses (20 points) ....................................................................................................... 15 

Page 3: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

1

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Tentamen: TDDB84 – Design Mönster (2009-10-15)

Examinator: Peter Bunus

Information Poängavdrag kommer att göras om punkterna nedan inte åtföljs!

1) Endast ett svar per blad. Använd endast framsidan (delfrågor kan vara på samma sida).

2) Sortera inlämnade svar med avseende på uppgiftsnummer i stigande ordning.

3) Svaren får vara på svenska eller engelska.

4) Dina svar skall tydligt visa lösningsmetod. Enbart rätt svar kommer inte att ge poäng. I det fall du är osäker på frågeställning, skriv ner din tolkning och lös uppgiften utifrån din tolkning.

5) Som hjälpmedel är boken av GOF eller liknande tillåtna och OH-bilderna från föreläsningar. Anteckningar i böcker, lösblad med egna anteckningar eller utskrifter är också okej.

Betygsgränser [0..50) poäng Betyg 2 [50..73) poäng Betyg 3 [73..85) poäng Betyg 4 [85..100] poäng Betyg 5

Lycka till!

Page 4: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

2 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Examination: TDDB84 – Design Pattern (2009-10-15)

Examiner: Peter Bunus

Information Please also observe the following; otherwise it might lead to subtraction of points:

1) Write only the answer to one task on one sheet. Use only the front side of the sheets (answers to subtasks can be on one page).

2) Sort the solution sheets according to the task number.

3) Answers may be in English or Swedish.

4) Your answers should clearly show solution methods, reasons, and arguments. Short answers should be motivated. If you have to a make an assumption about a question, write down the assumptions you make.

5) The GOF book or other design pattern related book is allowed during the exam. The printed lecture slides, other design pattern related printed material and own course notes are also allowed during the examination.

Grading To pass the exam you have to do at least 50 points from 100 possible. [0..50) points F [50..59) points E [59..70) points D [70..78) points C [78..85) points B [85..100] points A

Good Luck!

Bonne chance!

Viel Glück!

Sėkmės!

祝你好運

祝福

Page 5: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

3

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Task 1: Short Answer – Short Motivation (20 points / 2 points for each question)

1. You are writing a file explorer which list files from a directory. Each file element is represented as a class with a field describing filename, type (folder / file), size, and extension, and an icon image. To save memory space, you don't want the same file with the same attributes (for example type, extension, image, description...) to be represented as different objects. What pattern should be used?

Answer: A flyweight pattern should be used for this example. A Flyweight will help you to minimize the memory usage by sharing as much data as possible with other similar objects. One parts of the can be shares and can be put in an external data structure and pass them temporarily to the Flyweight object when they are used. In our example the icon describing a C/C++ header together with the type description can be stored in a separate object and passed to the Flyweight file object when it is needed.

2. Study the following classes below and select all correct statements below: 01: class CNeo{ 02: 03: static private CNeo instance = null; 04: 05: private CNeo () {} 06: 07: public static CNeo getInstance() { 08: if (instance == null) { 09: instance = new CNeo (); 10: } 11: return instance; 12: } 13: 14: public Object clone() throws CloneNotSupportedException { 15: throw new CloneNotSupportedException(); 16: } 17: } 01: class CAgent { 02: static private Map agents = new HashMap(); 03: 04: private CAgent () {} 05: 06: public static CAgent getInstance(String name) { 07: CAgent instance = (CAgent) agents.get(name); 08: if (instance == null) { 09: instance = new CAgent (); 10: agents.put(name, instance); 11: }

Page 6: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

4 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

12: 13: return instance; 14: } 15: }

a) Both classes implement the Singleton pattern.

b) The CNeo class implements the Singleton pattern, CAgent doesn't.

c) The CNeo class implements the Prototype pattern, CAgent implements the Factory Method.

d) The CAgent class implements the singleton pattern, CNeo doesn't.

e) Both classes encapsulate object creation.

f) Only the CNeo class encapsulates object creation.

g) Only the CAgent class encapsulates object creation.

h) None of the classes encapsulates object creation.

Answer: The correct answer is b) and e). The CNeo class represents the Singleton pattern, while the CAgent class is a static factory. The structures, of these patterns, are similar but their intent is very different. However both of them are encapsulating object creation.

3. Which of the following statements describe the Factory Method design pattern?

a) It relies on inheritance.

b) It reduces dependency on concrete classes.

c) It provides an interface for creating families of related objects without specifying their concrete classes.

Answer: a) and b) The Factory method lets a class defer instantiation to subclasses so it will rely on instantiation and of course the intent is to reduce the dependency of the client on concrete classes. We have used this pattern extensively when we wanted to adhere to the principle “Program to in interface and not to an implementation”. The third question describes the Abstract Factory pattern not the Factory Method Pattern.

4. "Class explosion" is having too many classes, each with slightly different behavior. Each

time you want to add some new method or some new instance variable, you need to update all your classes, doubling the number of classes each time. One way to avoid the "Class Explosion" is to use one of these patterns:

a) Adapter

b) Decorator

c) Abstract Factory

d) Proxy

e) Singleton

Answer: b) A way to avoid the class explosion is to use the Decorator pattern.

5. The following code is an implementation of which design pattern? Note that I can use the

sub-classes interchangeably in the context of Transportation class.

Page 7: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

5

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

interface Transporter { void transport(); } class Car implements Transporter { public void transport(){ System.out.println("Travel with car");} } class Bus implements Transporter { public void transport(){System.out.println("Travel with bus");} } class Train implements Transporter { public void transport(){System.out.println("Travel with train");} } class Transportation { Transporter tporter; public Transportation(Transporter t) { tporter = t; } public void transport() { tporter.transport(); } } class Example { public static void main(String[] args) { Transportation context = new Transportation(new Car()); context.transport(); context = new Transportation(new Bus()); context.transport(); } }

a) Chain of Responsibility

b) Bridge

c) Flyweight

d) Composite

e) Strategy

Answer: e) The Strategy Pattern. The context Transportation class can change the behavior dynamically due to the fact that the each way of transportation is encapsulated in a separate object (Car, Buss, Train) and can be used interchangeable.

6. Which pattern has the similar behavior as exceptions handling mechanism?

- The method where the exception occurs could treat the exception. - The method where the exception occurs could rethrow it to allow handle it at another layer.

The following Java code snippet illustrates the exception handling mechanism: try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new SampleException(e); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }

Page 8: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

6 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing. The first handler, in addition to printing a message, throws a user-defined exception and propagates the error up to a higher-level handler (a new SampleException exception is created with the original cause attached and the exception is thrown up to the next higher level exception handler).

Answer: The Chain of responsibility pattern avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

7. The following code is... 01: public class Singleton { 02: private Singleton() { } 03: 04: private static class SingletonHolder { 05: private static final Singleton instance = new Singleton(); 06: } 07: 08: public static Singleton getInstance() { 09: return SingletonHolder.instance; 10: } 11: }

a) ... not an implementation of the Singleton Pattern.

b) ... a valid implementation of the Singleton Pattern and the instance can be initialized safely in concurrent environments.

c) ... a valid implementation of the Singleton Pattern but the instance cannot be initialized safely in concurrent environments.

Answer: b) This was a very tricky question and I expected that only the very advanced Java programmers to give a correct answer and explanation. The code is a valid implementation of the Singleton Pattern also called lazy-loaded singleton or Initialization on Demand Holder. It's mainly used when initialization of the class is expensive and it cannot be done safely due to a highly concurrent environment. Let’s see how this works.

When the class Singleton is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition SingletonHolder within it is not initialized until the JVM determines that SingletonHolder must be executed. The static class SingletonHolder is only executed when the static method getInstance is invoked on the class Singleton, and the first time this happens the JVM will load and initialize the SingletonHolder class. The initialization of the SingletonHolder class results in static variable instance being initialized by executing the (private) constructor for the outer class Singleton. Since the class initialization phase is guaranteed by the JLS (Java Language Specification) to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization. And since the initialization phase writes the static variable something in a serial operation, all subsequent concurrent invocations of the getInstance will return the same correctly initialized something without incurring any additional synchronization overhead.

8. Let us say that you are writing an application that uses a third-party PDF rendering library and another third-party PDF text extraction library, both with complex APIs. You have written

Page 9: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

7

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

a single, simple interface over these complex APIs that your application can use for all of its PDF parsing needs. What pattern is this an example of?

a) Façade

b) Decorator

c) Adapter

d) Proxy

e) Composite

Answer: Facade is a way to layer over one or more existing interfaces with a different interface. Proxy and Decorator keep the same interface while the Adaptor will provide a different interface but it will not hide the complexity of the third party library

9. Which pattern is used by the example below? (Note: Don't pay too much attention to the names of the methods and classes. Usually when using this pattern specific names are used. But that's not the case in the sample to not make the answer too obvious.).

abstract class Shape { abstract void doAction(Action action); } class Circle extends Shape { void doAction(Action action) { action.doOnCircle(this); } } class Square extends Shape { void doAction(Action action) { action.doOnSquare(this); } } interface Action { void doOnSquare(Square square); void doOnCircle(Circle circle); } class DrawAction implements Action { public void doOnCircle(Circle circle) { // draw the circle... } public void doOnSquare(Square square) { // draw the square ... }

}

a) Chain of Responsibility

b) Visitor

c) Bridge

d) Strategy

e) Command

Page 10: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

8 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

f) Proxy

g) Mediator

h) Adapter

Answer: This is a an example of the Visitor pattern. The Action is the visitor, doAction is usually called "accept", and doOnSomething is called visitSomething. Drawing the UML diagram would have helped you a lot in answering this question

10. Check all that apply for the Memento Pattern

a) Is a structural pattern.

b) Violates encapsulation.

c) Allows the dynamic attachment of additional responsibilities to an object.

d) Defines an object that encapsulates how a set of objects interact.

e) None of the above.

Answer: Memento is a behavioral pattern that, without violating encapsulation, captures and externalizes an object's internal state (so that the object can be restored to this state later) . Thus, choices a) and b) are incorrect. Choices c) and d) respectively describe the Decorator and Mediator patterns, so only choice e) is correct.

Task 2: Airline Frequent Flyer Program (20 points) Consider a frequent flyer program run by an airline. A traveler starts out at, say, Basic level; then, as miles are accumulated by flying, she moves up to Silver or Gold level. At these levels, travelers can access lounges, get an extra baggage allowance, and also earn miles at a faster rate. For example, at the Silver tier, for every 1000 miles flown, a credit for 1250 miles is earned; at the Gold level, the credit is for 1500 miles. Other benefits also apply, as shown in the sample from Scandinavian Airlines in the table below:

SAS EuroBonus Basic

SAS EuroBonus Silver

SAS EuroBonus Gold

Access to SAS newsletter X X X

Car Rental Discount X X X

Priority on waiting lists X X

SAS 24h Hot Line Service X X

Business check in X X

Extra luggage X X

Lounge access X

Priority baggage handling X

SAS Fast track access X

Page 11: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

9

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

A frequent flyer program works in annual cycles: at the end of each year, a member’s activity is calculated for the year and she is assigned to a tier. In the case of our hypothetical program, one of the requirements is to fly 25,000 miles in one year to attain Silver status and keep it for the next year; for Gold status a member must fly 50,000 miles.

What design pattern or patterns shall be used to capture the Airline Frequent Flyer Program in a software application? Give a short explanation. In particular, show an appropriate class diagram(s) and enough code fragments to illustrate your use of the pattern to solve the problem.

Answer: For the sake of simplicity let’s start by giving some names to the functions that a traveler can access.

Access to SAS newsletter getNewsletter()

Car Rental Discount getCarDiscount()

Priority on waiting lists getWaitingListPriority()

SAS 24h Hot Line Service callHotLine()

Business check in businessCheckIn()

Extra luggage checkInLuggage()

Lounge access accesLounge()

Priority baggage handling baggagePriorityHandling()

SAS Fast track access fastTrackAcess()

The Airline Frequent Flyer Program is a typical example for the State Design Pattern. We van start first by drawing a simplified state diagram of the system.

NoCustomerBasic

Silver

Gold

flyMiles >=50 00flyMiles < 25 000

25 <= flyMiles < 50 000 flyMiles > 50 000

25 <= flyMiles < 50 000flyMiles < 25 000

Let us suppose that the starting state is when the traveler has not decided yet to join the freqvent flyer program. In our state diagram this state is called NoCustomer. Once the traveler decided to join the program he/she will “jump” into a state corresponding to a Basic membership level where only the getNewslater() and getCarDiscount() functions are available. “Jumping” from one state to another is done when some travelling is performed. A function called travel() will be responsible to change the state of the system once the condition imposed on the amount of flew miles is satisfied. Now we can take a look on the UML diagram of the system as well.

Page 12: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

10 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

+getNewsletter()+getCarDiscount()+getWaitingListPriority()+callHotLine()+businessCheckIn()+checkInLuggage(in weight : double)+accesLounge()+baggagePriorityHandling()+fastTrackAcess()+joinProgram(in context : CFrequentFlyer)+travel(in miles : double, in context : CFrequentFlyer) : double

CState

1 *

+joinProgram()+travel()+getNewsletter()+getCarDiscount()+getWaitingListPriority()+callHotLine()+businessCheckIn()+checkInLuggage(in weight : double)+accesLounge()+baggagePriorityHandling()+fastTrackAcess()+....()+setState()

-state : CStateCFrequentFlyer

public void baggagePriorityHandling() {state.baggagePriorityHandling();

}

public void setState(CState state){this.state = state;

}

Client

+getNewsletter()+getCarDiscount()+getWaitingListPriority()+callHotLine()+businessCheckIn()+checkInLuggage(in weight : double)+accesLounge()+baggagePriorityHandling()+fastTrackAcess()+joinProgram(in context : CFrequentFlyer)+travel(in miles : double, in context : CFrequentFlyer) : double

CNoCustomer

+getNewsletter()+getCarDiscount()+getWaitingListPriority()+callHotLine()+businessCheckIn()+checkInLuggage(in weight : double)+accesLounge()+baggagePriorityHandling()+fastTrackAcess()+joinProgram(in context : CFrequentFlyer)+travel(in miles : double, in context : CFrequentFlyer) : double

CBasic

+getNewsletter()+getCarDiscount()+getWaitingListPriority()+callHotLine()+businessCheckIn()+checkInLuggage(in weight : double)+accesLounge()+baggagePriorityHandling()+fastTrackAcess()+joinProgram(in context : CFrequentFlyer)+travel(in miles : double, in context : CFrequentFlyer) : double

CSilver

+getNewsletter()+getCarDiscount()+getWaitingListPriority()+callHotLine()+businessCheckIn()+checkInLuggage(in weight : double)+accesLounge()+baggagePriorityHandling()+fastTrackAcess()+joinProgram(in context : CFrequentFlyer)+travel(in miles : double, in context : CFrequentFlyer) : double

CGold

public void joinProgram(FrequentFlyer context) {System.out.println("Welcome to the SAS EuroBonus Program");context.setState(new CBasic());

}

public double travel(int miles, FrequentFlyer context) {if(context.flyMiles >= 25000 && context.flyMiles > 50000)

context.setState(new CSilver());if(context.flyMiles >= 50000)

context.setState(new CGold());return miles;

}

You should notice that the travel() function in each state is responsible for checking the number of miles and “jump” to a different state if it is necessary. A simplified UML diagram is also given below

It was very important for this example to show that certain member functions form the states can actually change the state of the system.

Task 3: Facebook (20 points) I guess most of you have already have Facebook account or have used other social networking application. In principle a social network service focuses on building online communities of people who share interests and/or activities, or who are interested in exploring the interests and activities of others. Facebook support groups that people can join. Each group has a title,

Page 13: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

11

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

administrative members, a group type (open/ closed), and a list of related groups. The figure below shows the TDDB84 group on Facebook that many of you have already joined.

Otherwise, a group operates just like an ordinary page. If somebody writes on the wall page of the group, the information is broadcasted to all the members and it is visualized in the news feeds of the members.

Which design pattern is the most appropriate to handle this basic functionality of such a Facebook group? Users should be able to join a group as well as leave a group if they get bored. Once a user has joined a group it will automatically receive any updates that are published on the wall. Give a short explanation. In particular, show an appropriate class diagram(s) and enough code fragments to illustrate your use of the pattern to solve the problem.

Page 14: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

12 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

Answer: The Observer Patter will suit well this type of application. The Facebook group needs to maintain a list of users. The users will act like observers and each time the state of the group changes the users will be notified by calling their Update() method through the Notify() function in the FacebookSubject. The Notify function will browse all the registered users and call their Update method to broadcast the new posted message on the wall. You should also notice that each user has now the possibility writing on the group wall using the WriteOnTheWall() function that will change the state of the FacebookGroup object.

+Update()

FacebookObserver

+Update()+WriteOnTheWall()

FacebookUser

+AddUser(in user : FacebookObserver)+RemoveUser(in user : FacebookObserver)+Notify()

-listUsersFacebookSubject

public void Notify() { Iterator i = listUsers.iterator(); while (i.hasNext()) {

FacebookObserver o = (FacebookObserver) i.next(); o.Update();

} }

+SetState(in walltext : string)+GetState()

-wallState : stringFacebookGroup

return wallState;

wallState = walltext;

void Update(){printWallMessageToNews(group.GetState());

}

+Update()+WriteOnTheWall()

FacebookAdmingroup group

void WriteOnTheWall(Strin message){group.SetState("I'm writting on the Wall");

} An example of the test application at the client level is given below: public static void main(String[] args) { System.out.println("Testing the Facebook Application"); //Create a group FacebookGroup tddb84 = new FacebookGroup(); //Create users FacebookUser user1 = new FacebookUser(tddb84, "Nick Nolte", 36); FacebookUser user2 = new FacebookUser(tddb84, "Bryan Adams", 53); FacebookUser user3 = new FacebookUser(tddb84, "Sarah Connor", 23); //Add users to the newly created group tddb84.addUser(user1); tddb84.addUser(user2); tddb84.addUser(user3); //write something on the wall tddb84.setState("Hello World"); tddb84.Notify(); //users can also write on the wall user1.writeOnTheWall("Hi"); tddb84.Notify();

}

Page 15: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

13

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

In order to get all the points allocated to this example I would have expected to clearly see the state change notification mechanism by invoking the Update functions in the Observers as well as the possibility of setting and getting the state of the Facebook Group.

The source code of a Java test implementation is available on the web page.

Task 4: Facebook Continued (20 points) Now let’s suppose that you would like to extend the functionality of Facebook group that you have created in Task 3 by adding the possibility that besides normal users a group page can also be a member of another group. As an example it should be possible that the group page of the “Ford Mustang” car lovers joins the “TDDB84 Design Patterns” group. As a consequence all the members of the “Ford Mustang” group become automatically members of the “TDDB84 Design Patterns” group.

a) Which design pattern is most appropriate to accommodate this change? How the solution proposed in the previous example shall be extended. Please give a short explanation why. Show an appropriate class diagram(s) and enough code fragments to illustrate your use of the pattern to solve the problem.

In order to accommodate the new requirement that groups can also contain other groups and not only users you will need to use the Composite Design Pattern. Now here comes the tricky part. The Coposite Design Pattern will use the FacebookUser as a leaf and the FacebookGroup as a composite object because groups can contain other groups and/or users. If we want to extend the solution from Task 3 we realize that actually the FacebookGroup is the Subject of the Observer Pattern but we need somehow to make it a Composite as well. Well, it might look strange but actually we can do that by making the FacebookSubject a specialization of the FacebookObserver so now the FacebookGroup is an observer and a composite in the same time. The modification to the previous solution are indicated by the red relationships in the figure below.

Since now the FacebooGroup is an observer as well we need to provide and implementation of the Update Function as well.

The source code of a Java test implementation is available on the web page.

Once we have the functionality described above we would like to use some of the applications that are providing user statistics based on information extracted from the members. The figures

Page 16: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

14 TDDB84 2009-10-15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

below depict some demographics statistics from the TDDB84 group computed by a tool called Insight. As you can see the TDDB84 Design Patterns group is not very popular among the female students .

Page 17: Tentamen TDDB84 (Design Mönster) Examination TDDB84 ...TDDB84/exam/2009/TentaTDDB84_HT09_SO… · Answer: A flyweight pattern should be used for this example. A Flyweight will help

15

Linköping University, Department of Computer and Information Science SE 581-83 Linköping Sweden

b) Which design pattern can be used by the Insight application to produce the demographics statistic? How would you modify your previous design to accommodate third party tools like Insight to browse the list of users and produces various type of statistics based on information gathered from the user’s profile. Don’t forget that now groups can be also members of other groups. Show an appropriate class diagram(s) and enough code fragments to illustrate your use of the pattern to solve this problem.

The Insight third party application need to traverse the list of users for each group and access the users internal data in order to produce the above mentioned statistics. The Visitor Pattern will allow us to add operations to the Composite structure that we have created previously without changing the structure itself. The UML diagram below shows the necessary modifications that need to be performed on the Composite structure in order to accommodate a visitor. Each class in the Composite structure need to add an acceptVisitor method-

+Update(in visitor : FacebookVisitor)+acceptVisitor(in visitor : FacebookVisitor)

FacebookObserver

+Update()+WriteOnTheWall()+acceptVisitor(in visitor : FacebookVisitor)

FacebookUser

+AddUser(in user : FacebookObserver)+RemoveUser(in user : FacebookObserver)+Notify()+Update()+acceptVisitor(in visitor : FacebookVisitor)

-listUsersFacebookSubject

+SetState(in walltext : string)+GetState()+Update()+acceptVisitor(in visitor : FacebookVisitor)

-wallState : stringFacebookGroup

+Update()+WriteOnTheWall()+acceptVisitor(in visitor : FacebookVisitor)

FacebookAdmingroup group

group

+visit(in group : FacebookGroup)+visit(in user : FacebookUser)

FacebookVisitor

+visit(in group : FacebookGroup)+visit(in user : FacebookUser)

AverageAgeVisitor

public void acceptVisitor(FacebookVisitor visitor){visitor.visit(this);

};

public void acceptVisitor(FacebookVisitor visitor){visitor.visit(this);

};

Task 5: Managing Courses (20 points) Design a simple system that manages courses offered by the Department of Computer Science at Linköping University (e.g., TDDB84 Design Patterns, TDDD12 Databases TDDD25 Distributed Systems, etc). Identify some of the attributes that each course should have- length, examination form, topics, etc. Most of the attributes of these courses are common like the list of possible lecture rooms, examination form or the hardware requirements for the labs, etc. Since we need to store a lot of information associated to each course we can imagine that the corresponding classes will have a high memory requirement and the time to instantiate them will be very long. Create the skeleton of a little test program that enables users to select a course, get a copy of it, and fill in details to enroll for the course. Use a design pattern that you think that would be appropriate for such an application. Show an appropriate class diagram(s) for this application.

Depending on the assumptions you made, the Prototype or the Flyweight Design Pattern could have been used.