CS12420 An Intro to Design Patterns Lynda Thomas [email protected].

34
CS12420 An Intro to Design Patterns Lynda Thomas [email protected]

Transcript of CS12420 An Intro to Design Patterns Lynda Thomas [email protected].

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

CS12420 An Intro to Design Patterns

Lynda Thomas

[email protected]

Page 2: 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

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

• 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

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

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

…..

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

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, ….

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

…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.

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

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

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

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!

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

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’

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

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.

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

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)

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

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

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

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)

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

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

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

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)

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

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

Stack

Stack

Diagrammatic View

javadoc view

Java source

Model

View 1 View 2

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

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;

}

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

Look at the bank example in the examples code from Topic00

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

• 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

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

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

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

This is what is set up in background

Account

Manager DebtCollector

Vector of Observers

setChanged();notifyObservers();

update() messages reflect changes

Observable Observer Observer

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

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.

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

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

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

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

and also added another Observer

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

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

}}

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

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

}

………}

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

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()); }

}

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

/** * 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)

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

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"); }

} }

Page 30: CS12420 An Intro to Design Patterns Lynda Thomas ltt@aber.ac.uk.
Page 31: CS12420 An Intro to Design Patterns Lynda Thomas ltt@aber.ac.uk.
Page 32: CS12420 An Intro to Design Patterns Lynda Thomas ltt@aber.ac.uk.

<<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

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

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.

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

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).