CS12420 An Intro to Design Patterns Lynda Thomas ltt@aber.ac.uk

Preview:

Citation preview

CS12420 An Intro to Design Patterns

Lynda Thomas

ltt@aber.ac.uk

In This Lecture

• Design Patterns

• How to write ‘good’ code in any setting

• In CS211 – you will see lots of examples

• Here I am concentrating on ones that relate to building GUIs

• Both are ways to facilitate Reuse.

• Capture knowledge for recurring use.• Frameworks: focus on concrete designs, algorithms and

implementations in a particular language

• Patterns: focus on reuse of abstract designs and small collections of cooperating classes - “a proven solution to a problem in a well-defined context”

Patterns vs. Frameworks

Frameworks

• Application Frameworks: encapsulate expertise in a ‘horizontal’ way across client domains eg. payroll systems, GIS systems

• Domain Frameworks: encapsulate ‘vertical’ expertise in a problem domain eg. Banking, manufacturing, drawing

• Support Frameworks: system level services such as file access, distributed computing, Swing

…..

Patterns - Origins

• Christopher Alexander’s Architecture Book “A Pattern Language” (network of patterns for architecture)

• A design pattern is a formal way of documenting a solution to a design problem in a particular field of expertise.

• Must show situation, problems, solution, several applications, ….

…and the world of OO design

• Gamma et al. ‘The Gang of Four’ 1995

• Conferences like OOPSLA

• Patterns Home Page www.hillside.net/patternsFundamental to any science or engineering discipline is a common vocabulary

for expressing its concepts, and a language for relating them together. The goal of patterns within the software community is to create a body of literature to help software developers resolve recurring problems encountered throughout all of software development. Patterns help create a shared language for communicating insight and experience about these problems and their solutions.

Patterns - How expressed

• Patterns need to be expressed so that they can be used in lots of different situations (rule of three)

• They must show the user: when to use them and how to use them but ...

• … they can’t be completely automated

Typical Pattern ‘Template’

• Name and Aliases

• Problem to solve

• Context

• Forces acting on the matter

• Solution

• Consequences

• Rationale

• Known Uses

• Related Patterns

• Author, Date, References, Keywords

• ExampleA ‘Template’ is a way of writing something –

funnily enough it is itself a pattern!

Example from Alexander

Name – ‘Different Chairs’Problem to solve – People need to sit down. Context – modern ‘dining sets’ make all chairs the same sizeForces acting on the matter – short, tall, thin, fat, old young

people; we project our moods onto chairs; use chairs in different ways: working, eating, playing games

Solution - Never furnish a place with chairs that are identicalConsequences – People will be comfortableRelated Patterns – ‘Pools of Light’

Example from management(again uses slightly different template)

SelfSelectingTeam (from Coplein)

. . . SizeTheOrganization revealed the need for a small, select team.

How do you staff such a team?

* * *

• The worst team dynamics can be found in appointed teams.

• There are no perfect criteria for screening team members. Yet broad interests (music and poetry for, example) seem to indicate successful team players.

• Teams staffed with such individuals are often willing to take extraordinary measures to meet project goals.

• However, when such interests are ignored, or when team members are appointed, team dynamics can suffer, greatly diminishing the productivity of a team.

Therefore:

• Create enthusiastic teams by empowering people to self-select their teams. Do limited screening on the basis of track record and broader interests.

• Such teams often, but not always, come about of their own volition. Sometimes, a PatronRole or other leader can seed the idea of such a team first as a rallying point for the formation of the team.

* * *

A SoloVirtuoso or ApprenticeShip role may self-select a team. FormFollowsFunction can give such a team its structure. DiverseGroups can help in the screening process. Temporary SelfSelectingTeam's can come together to work on ProgrammingEpisode's.

We will look at OO design patterns in a minute but ….

what other patterns can you discover? • As a consumer• As a person sharing accommodation• As a team worker• As a parent (or a person with parents)

Gang of Four Patterns

• Creational Patterns: abstract factory, builder, factory method, prototype, singleton

• Structural Patterns: adapter, bridge, composite, decorator, façade, flyweight, proxy

• Behavioural Patterns: Chain of responsibility, command, interpreter, iterator, mediator, memento, observer, state, strategy, template, visitor

Patterns we’ve seen that have become part of Java

• Composite – the entire idea of class with attributes is a pattern (now also part of languages like Java)

• Iterator – allows you to move through a collection of data using a standard interface without needing to know the details of implementation (likewise, in the for each loop)

• Template – leave details to be implemented in subclasses (this is what Abstract Classes and Interfaces are about)

2 ‘new’ patterns ….

MVC (Model View Controller) and

Observer – Observable

both keep the Model (the logic and the data) separate from View and Controller (the way you see and manipulate it)

View Controller

Model

Our (better) Swing Code has MVC flavour

The idea is that the model is the underlying data

The view is a display of it

The controller controls what you do with it

Consider the Counter code…..

Or consider Eclipse/BlueJ etc……(next page)

public class Stack { public void Stack(……. }

Stack

Stack

Diagrammatic View

javadoc view

Java source

Model

View 1 View 2

The basic look of an MVC program:

public class Model{

//all code about data

//could include testing code

}

public class Display extends JFrame{

//code to change and display model

//actually probably lots of classes: panels, listeners, etc etc

//in this case the View and the Controller lumped together

private Model model;

}

Look at the bank example in the examples code from Topic00

• MVC has found itself into Java now in the Struts Framework

• It can also be modelled using Observer/Observable (which is a pattern in its own right and also in Java)

• This sometimes gets around the ‘too much linking’ problem that you may be starting to feel about Swing

Observer/Observable

• The idea is that any class that is to be monitored needs to extend the Observable class.

• The class that watches (and responds) implements the Observer interface

This is what is set up in background

Account

Manager DebtCollector

Vector of Observers

setChanged();notifyObservers();

update() messages reflect changes

Observable Observer Observer

By extending Observable, the following methods (among others) become available:

• addObserver(Observer o)Records the fact that an Observer is monitoring the

Observable object. Reference to all Observers is kept in an internal table.

• notifyObservers() & notifyObservers(Object arg)If the object has changed then calls the update()

method of all the observer objects recorded in Observer table. (arg can be anything to be passed to Observers)

• setChanged()Should be called before notifyObservers() method.

Meanwhile, Observer must implement one method:

• update(Observable obs, Object o)

This method is called whenever the observed object is changed. The second parameter is just there so you can pass some information too (see last page).

It is the responsibility of the Observable thing to call notifyObservers() and setChanged() when it wants to have this method called in the Observer(s) – note the actual calling of update is automatic

The Bank again using Obs/ObsNow, rewritten using Observer/Observable

and also added another Observer

Here is what runs this

public class Demo{

public static void main(String args[]) { Account account; //model BankAccountView view1; //frame contains view 1 ManagerView view2; //frame is view 2 account=new Account();

view1=new BankAccountView(account); view2=new ManagerView();

account.addObserver(view2); //panel within view1 // is other Observer

}}

First the Model (Observable)

public class Account extends Observable{ private double balance =0;

public void withdraw(double amt) { balance -= amt; setChanged(); notifyObservers(); //can have an object in brackets

}

………}

Now a really simple Observer View

/** * This class provides an absolutely bare bones view of * what is in the account object * done with observer/observable so automatically updated */public class ManagerView extends JFrame implements Observer{ private JLabel label;

public ManagerView() { … }

/** * gets called when model is updated */ public void update(Observable acc,Object blank) {

//must have an Object in params too but not used double balance=((Account)acc).getBalance(); label.setText(new Double(balance).toString()); }

}

/** * This class implements Observer, picks up what has * happened to account and displays */public class TextPanel extends JPanel implements Observer{ private JTextField inputField; private JLabel balanceField; public TextPanel() { …. } …. /** * gets called when model is updated */ public void update(Observable acc,Object blank) {

//must have an Object in params too but not used double balance=((Account)acc).getBalance(); balanceField.setText(new Double(balance).toString()); } }

Now the main Observer View (in a Panel in a Frame)

Also have to consider the controller, which here is implemented in the ButtonPanel and the Listener

public class AccountListener implements ActionListener{ private TextPanel textPanel; //needs a link to here so can get input private Account account; //model public AccountListener(TextPanel tp, Account acc) { textPanel=tp; account=acc; } /** * called when button pressed * gets amount and updates the model */ public void actionPerformed(ActionEvent e) { String action=e.getActionCommand(); try{ double amount=(textPanel.getInputField()); if (action.equals("Withdraw")) account.withdraw(amount); else //deposit account.deposit(amount); } catch(NumberFormatException n) { JOptionPane.showMessageDialog(null, "Enter an amount"); }

} }

<<interface>>Observer

Observable

Account

ButtonPanel

BankAccountView

ManagerView

Demo+main()

AccountListenerListens to

ButtonPanel

TextPanel

<<interface>>ActionListener

Purple things are

part of Java

1..1

1..1

1..1

1..1

1..1

Someone asked for this – not sure how much it helps but here you are

Resources

• A document that explains the Bank Example more• Code for bank example

If it seems like the edges of the topics MVC and Observer/Observable are blurry that is because they are.

You will do more patterns in CS211.

In This Lecture

• Patterns, particularly Observer/Observable

• Worksheet 3Look at the code for the Observer/Observable implementation of the Bank (see content section of

Blackboard)Currently there are 2 different views of the account.

Add a third view as an Observer - it doesn't matter what, use your imagination.You can use the Manager View as a starting place but display something other than the account balance.(If you have no imagination, then how about displaying a box that is sized relative to the account balance - the code for drawing things is in the drawing.zip file in the Drawing and IMages item under content - you could make the box red for negative balances and green for positive ones).