27
1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

Embed Size (px)

Citation preview

Page 1: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

1

TCSS 360, Spring 2005Lecture Notes

Design Patterns:Factory, Command

Page 2: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

2

Outline

What are design patterns? Why should we study them?

List of all design pattern names and categories

Factory pattern

Command pattern

Page 3: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

3

Design challenges Designing software for reuse is hard; one must find:

a good problem decomposition, and the right software abstractions

a design with flexibility, modularity and elegance

designs often emerge from an iterative process (trials and many errors)

successful designs do exist two designs they are almost never identical they exhibit some recurring characteristics

The engineering perspective: can designs be described, codified or standardized?

this would short circuit the trial and error phase produce "better" software faster

Page 4: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

4

Design patterns history

the concept of a "pattern" was first expressed in Christopher Alexander's work A Pattern Language in 1977 (2543 patterns)

in 1990 a group called the Gang of Four or "GoF" (Gamma, Helm, Johnson, Vlissides) compile a catalog of design patterns

design pattern: a solution to a common software problem in a context example: Iterator pattern

The Iterator pattern defines an interface that declares methods for sequentially accessing the objects in a collection.

Page 5: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

5

More about patterns A pattern describes a recurring software structure

is abstract from concrete design elements such as problem domain, programming language

identifies classes that play a role in the solution to a problem, describes their collaborations and responsibilities

lists implementation trade-offs patterns are not code or designs; must be instantiated/applied

the software engineer is required to: evaluate trade-offs and impact of using a pattern in the system

at hand make design and implementation decision how best to apply

the pattern, perhaps modify it slightly implement the pattern in code and combine it with other

patterns

Page 6: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

6

Benefits of using patterns patterns are a common design vocabulary

allows engineers to abstract a problem and talk about that abstraction in isolation from its implementation

embodies a culture; domain specific patterns increase design speed

patterns capture design expertise and allow that expertise to be communicated promotes design reuse and avoid mistakes

improve documentation (less is needed) and understandability (patterns are described well once)

Page 7: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

7

Gang of Four (GoF) patterns

Creational Patterns(concerned with abstracting the object-instantiation process)

Factory Method Abstract Factory Singleton Builder Prototype

Structural Patterns(concerned with how objects/classes can be combined to form larger structures)

Adapter BridgeComposite

Decorator Facade Flyweight Proxy

Behavioral Patterns(concerned with communication between objects)

Command Interpreter Iterator Mediator Observer State Strategy Chain of Responsibility Visitor Template Method

Page 8: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

8

Pattern: Factory(a variation of Factory Method, Abstract Factory)

a class used to create other objects

Page 9: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

9

Problem: Bulky GUI code GUI code to construct many components

quickly becomes redundant (here, with menus): homestarItem = new JMenuItem("Homestar Runner"); homestarItem.addActionListener(this); viewMenu.add(homestarItem); crapItem = new JMenuItem("Crappy"); crapItem.addActionListener(this); viewMenu.add(crapItem);

another example (with buttons): button1 = new JButton(); button1.addActionListener(this); button1.setBorderPainted(false);

button2 = new JButton(); button2.addActionListener(this); button2.setBorderPainted(false);

Page 10: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

10

Factory pattern Factory: a class whose sole job is to easily

create and return instances of other classes

a creational pattern; makes it easier to construct complex objects

instead of calling a constructor, use a static method in a "factory" class to set up the object

saves lines and complexity to quickly construct / initialize objects

examples in Java: borders (BorderFactory), key strokes (KeyStroke), network connections (SocketFactory)

Page 11: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

11

Using existing factories in Java

setting borders on buttons and panels use built-in BorderFactory class

myButton.setBorder(

BorderFactory.createRaisedBevelBorder());

setting hot-key "accelerators" on menus use built-in KeyStroke class

menuItem.setAccelerator( KeyStroke.getKeyStroke('T',

KeyEvent.ALT_MASK));

Page 12: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

12

Factory implementation details

when implementing a factory of your own: the factory itself should not be instantiated

make constructor private factory only uses static methods to construct

components factory should offer as simple an interface to

client code as possible don't demand lots of arguments; possibly overload

factory methods to handle special cases that need more arguments

factories are often designed for reuse on a later project or for general use throughout your system

Page 13: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

13

Factory sequence diagram

Page 14: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

14

Factory examplepublic class ButtonFactory { private ButtonFactory() {}

public static JButton createButton( String text, ActionListener listener, Container panel)

{ JButton button = new JButton(text); button.setMnemonic(text.charAt(0)); button.addActionListener(listener); panel.add(button); return button; }}

Page 15: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

15

GoF's variations on Factory

Factory Method pattern: a factory that can be constructed and has an overridable method to create its objects can be subclassed to make new kinds of factories

Abstract Factory pattern: when the topmost factory class and its creational method are abstract

Page 16: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

16

Pattern: Command

objects that represent actions

Page 17: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

17

Open-closed principle Open-Closed Principle: Software entities like

classes, modules and functions should be open for extension but closed for modifications.

The Open-Closed Principle encourages software developers to design and write code in a fashion that adding new functionality would involve minimal changes to existing code. most changes will be handled as new methods and

new classes designs following this principle would result in

resilient code which does not break on addition of new functionality

Page 18: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

18

Bad event-handling codepublic class TTTGui implements ActionListener { ...

public void actionPerformed(ActionEvent event) { if (event.getSource() == view1Item){

// switch to view #1 ...

else { // event source must be view2Item

// switch to view #2 ...

} }}

in this code, the "master" TTT GUI object is in charge of all action events in the UI is this bad? what could happen if we add another action event

source?

Page 19: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

19

Common UI commands it is common in a GUI to have several ways to

activate the same behavior example: toolbar "Cut" button and "Edit / Cut" menu this is good ; it makes the program flexible for the

user we'd like to make sure the code implementing these

common commands is not duplicated

Page 20: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

20

Solution: Action,AbstractAction

Java's Action interface represents a UI command a UI command has a text name, an icon, an action to run can define multiple UI widgets that share a common

underlying command by attaching the same Action to them These Swing components support Action

JButton(Action a) JToggleButton(Action a) JCheckBox(Action a) JMenuItem(Action a) JRadioButton(Action a)

AbstractAction class implements Action and maintains an internal map of keys to values

each key represents a name of a property of the action (e.g. "Name") each value represents the value for that property (e.g. "Save Game") can be used to ensure that all UI components that share a common UI

action will have the same text, icon, hotkey

Page 21: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

21

ActionListener and Action code

reminder: interface ActionListener public void actionPerformed(ActionEvent e)

interface Action extends ActionListener adds property enabled

isEnabled() / setEnabled(boolean)

abstract class AbstractAction implements Action you must still write actionPerformed

Page 22: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

22

AbstractAction members public class AbstractAction implements Action

public AbstractAction(String name) public AbstractAction(String name, Icon icon) public Object getValue(String key) public boolean isEnabled() public void putValue(String key, Object value) public void setEnabled(boolean enabled) ...

AbstractAction object maintains an internal map of keys to values

each key represents a name of a property of the action (e.g. "Name")

each value represents the value for that property (e.g. "Save Game")

Page 23: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

23

Using Action, example define a class that extends AbstractAction: public class CutAction extends AbstractAction { public CutAction() { super("Cut", new ImageIcon("cut.gif")); }

public void actionPerformed(ActionEvent e) { // do the action here ... } }

create an object of this class, attach it to UI objects: CutAction cut = new CutAction(); JButton cutButton = new JButton(cut); JMenuItem cutMItem = new JMenuItem(cut);

now the same action will occur in both places; also, changes to the action will be seen on both widgets:

cut.setEnabled(false);

Page 24: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

24

Action and Swing components

Other uses: properties of the action can be set cut.putValue(Action.SHORT_DESCRIPTION, "Cuts the selected text");

will use this label for the tooltip text

cut.putValue(Action.NAME, "Cut"); will use the text label "Cut" for the name of the command

cut.putValue(Action.MNEMONIC_KEY, new Integer('T'));

will underline 't' in "Cut" as a mnemonic hotkey for the command

cut.putValue(Action. ACCELERATOR_KEY, KeyStroke.getKeyStroke('X', KeyEvent.CTRL_MASK));

will use Ctrl-X as an accelerator hotkey for the command

Page 25: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

25

Command pattern Command: an object that represents an

action sometimes called a "functor" to represent an

object whose sole goal is to encapsulate one function

Java API examples: ActionListener, Comparator, Runnable / Thread

Page 26: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

26

Command pattern applications

command objects serve as a "model" of commands: separates the user interface from them each model can support multiple views each action can support multiple widgets

use the Command pattern when you want to: implement a callback function capability have several UI widgets that cause the same action

to occur specify, queue, and execute requests at different

times support undo and change log operations

Page 27: 1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command

27

References Java API pages

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Action.html http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/

AbstractAction.html

Cunningham & Cunningham OO Consultancy, Inc. http://c2.com/cgi/wiki?AbstractFactoryPattern http://c2.com/cgi/wiki?FactoryMethodPattern http://c2.com/cgi/wiki?CommandPattern

Design Patterns Java Companion http://www.patterndepot.com/put/8/JavaPatterns.htm

Design Pattern Synopses http://www.mindspring.com/~mgrand/pattern_synopses.htm