09-Patterns Factory Command

Embed Size (px)

DESCRIPTION

Patterns Factory Command

Citation preview

  • TCSS 360, Spring 2005Lecture NotesDesign Patterns:Factory, Command

  • OutlineWhat are design patterns? Why should we study them?

    List of all design pattern names and categories

    Factory pattern

    Command pattern

  • Design challengesDesigning software for reuse is hard; one must find:a good problem decomposition, and the right software abstractionsa design with flexibility, modularity and elegance

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

    successful designs do existtwo designs they are almost never identicalthey exhibit some recurring characteristics

    The engineering perspective: can designs be described, codified or standardized?this would short circuit the trial and error phaseproduce "better" software faster

  • Design patternshistorythe 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 contextexample: Iterator pattern The Iterator pattern defines an interface that declares methods for sequentially accessing the objects in a collection.

  • More about patternsA pattern describes a recurring software structureis abstract from concrete design elements such as problem domain, programming languageidentifies classes that play a role in the solution to a problem, describes their collaborations and responsibilitieslists implementation trade-offspatterns 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 handmake design and implementation decision how best to apply the pattern, perhaps modify it slightlyimplement the pattern in code and combine it with other patterns

  • Benefits of using patternspatterns are a common design vocabularyallows engineers to abstract a problem and talk about that abstraction in isolation from its implementationembodies a culture; domain specific patterns increase design speed

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

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

  • Gang of Four (GoF) patternsCreational Patterns (concerned with abstracting the object-instantiation process)Factory MethodAbstract FactorySingletonBuilderPrototype

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

    Behavioral Patterns (concerned with communication between objects)CommandInterpreterIteratorMediatorObserverStateStrategyChain of ResponsibilityVisitorTemplate Method

  • Pattern: Factory(a variation of Factory Method, Abstract Factory)a class used to create other objects

  • Problem: Bulky GUI codeGUI 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);

  • Factory patternFactory: a class whose sole job is to easily create and return instances of other classes

    a creational pattern; makes it easier to construct complex objectsinstead of calling a constructor, use a static method in a "factory" class to set up the objectsaves lines and complexity to quickly construct / initialize objectsexamples in Java: borders (BorderFactory), key strokes (KeyStroke), network connections (SocketFactory)

  • Using existing factories in Javasetting borders on buttons and panelsuse built-in BorderFactory class myButton.setBorder( BorderFactory.createRaisedBevelBorder());

    setting hot-key "accelerators" on menususe built-in KeyStroke class menuItem.setAccelerator( KeyStroke.getKeyStroke('T', KeyEvent.ALT_MASK));

  • Factory implementation detailswhen implementing a factory of your own:the factory itself should not be instantiatedmake constructor privatefactory only uses static methods to construct componentsfactory should offer as simple an interface to client code as possibledon't demand lots of arguments; possibly overload factory methods to handle special cases that need more argumentsfactories are often designed for reuse on a later project or for general use throughout your system

  • Factory sequence diagram

  • 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; }}

  • GoF's variations on FactoryFactory Method pattern: a factory that can be constructed and has an overridable method to create its objectscan be subclassed to make new kinds of factoriesAbstract Factory pattern: when the topmost factory class and its creational method are abstract

  • Pattern: Commandobjects that represent actions

  • Open-closed principleOpen-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 classesdesigns following this principle would result in resilient code which does not break on addition of new functionality

  • 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 UIis this bad?what could happen if we add another action event source?

  • Common UI commandsit is common in a GUI to have several ways to activate the same behaviorexample: toolbar "Cut" button and "Edit / Cut" menuthis is good ; it makes the program flexible for the userwe'd like to make sure the code implementing these common commands is not duplicated

  • Solution: Action,AbstractActionJava's Action interface represents a UI commanda UI command has a text name, an icon, an action to runcan define multiple UI widgets that share a common underlying command by attaching the same Action to themThese Swing components support ActionJButton(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 valueseach 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

  • ActionListener and Action codereminder: interface ActionListenerpublic void actionPerformed(ActionEvent e)

    interface Action extends ActionListeneradds property enabled isEnabled() / setEnabled(boolean)

    abstract class AbstractAction implements Actionyou must still write actionPerformed

  • AbstractAction memberspublic class AbstractAction implements Actionpublic 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 valueseach 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")

  • Using Action, exampledefine 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);

  • Action and Swing componentsOther uses: properties of the action can be setcut.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

  • Command patternCommand: an object that represents an actionsometimes called a "functor" to represent an object whose sole goal is to encapsulate one function

    Java API examples:ActionListener, Comparator, Runnable / Thread

  • Command pattern applicationscommand objects serve as a "model" of commands:separates the user interface from themeach model can support multiple viewseach action can support multiple widgets

    use the Command pattern when you want to:implement a callback function capabilityhave several UI widgets that cause the same action to occurspecify, queue, and execute requests at different timessupport undo and change log operations

  • ReferencesJava API pageshttp://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Action.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/javax/swing/AbstractAction.html

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

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

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