Lecture on Design Patterns: Factory, Command

Slides:



Advertisements
Similar presentations
Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
Advertisements

DESIGN PATTERNS OZGUR RAHMI DONMEZ.
Patterns Reusable solutions to common object-oriented programming problems When given a programming problem, re-use an existing solution. Gang of Four.
05/26/2004www.indyjug.net1 Indy Java User’s Group June Knowledge Services, Inc.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
CSSE 374: 3½ Gang of Four Design Patterns These slides derived from Steve Chenoweth, Shawn Bohner, Curt Clifton, and others involved in delivering 374.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
January 12, Introduction to Design Patterns Tim Burke References: –Gamma, Erich, et. al. (AKA, The Gang of Four). Design Patterns: Elements of Reusable.
Creational Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
1 CSE 403 Design Patterns: Singleton, Memento, Flyweight, Factory, Command Reading: Simply Singleton and Make Your Apps Fly (R. Geary) These lecture slides.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
CSE 432: Design Patterns Introduction What’s a Pattern? What’s an Idiom? According to Alexander, a pattern: –Describes a recurring problem –Describes the.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
CSE 403, Spring 2008, Alverson Software Design “There are two ways of constructing a software design: one way is to make it so simple that there are obviously.
ECE450S – Software Engineering II
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
05/26/2004www.indyjug.net1 Indy Java User’s Group May Knowledge Services, Inc.
CSC 480 Software Engineering Design With Patterns.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Design Patterns. 1 Paradigm4 Concepts 9 Principles23 Patterns.
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
CS251 – Software Engineering Lectures 18: Intro to DP Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others 1 و ابتغ فيما آتاك الله الدار.
Design Patterns Introduction “Patterns are discovered, not invented” Richard Helm.
Interface Patterns. Adapter Provides the interface a client expects, using the services of a class with a different interface Note Avoid using object.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
CSCI 3428: Software Engineering Tami Meredith Chapter 5 Design Patterns.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
Design Patterns: MORE Examples
The Object-Oriented Thought Process Chapter 15
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Software Design Patterns
MPCS – Advanced java Programming
Introduction to Design Patterns
Design Patterns Lecture part 2.
Introduction to Design Patterns
object oriented Principles of software design
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2005 Instructor: Patrice Chalin.
WARNING These slides are not optimized for printing or exam preparation. These are for lecture delivery only. These slides are made for PowerPoint 2010.
Software Engineering Lecture 7 - Design Patterns
Informatics 122 Software Design II
CSE 403 Design Patterns: Singleton, Flyweight, Factory, Command, Memento Reading: Simply Singleton and Make Your Apps Fly (R. Geary) These lecture slides.
CSC 480 Software Engineering
DESIGN PATTERNS : Introduction
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2004 Instructor: Patrice Chalin.
Design Patterns Imran Rashid CTO at ManiWeber Technologies.
Informatics 122 Software Design II
CSC 480 Software Engineering
Presentation transcript:

Lecture on Design Patterns: Factory, Command www.AssignmentPoint.com www.assignmentpoint.com

Outline What are design patterns? Why should we study them? List of all design pattern names and categories Factory pattern Command pattern

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

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.

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

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)

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 Bridge Composite Decorator Facade Flyweight Proxy Behavioral Patterns (concerned with communication between objects) Command Interpreter Iterator Mediator Observer State Strategy Chain of Responsibility Visitor Template Method

Pattern: Factory (a variation of Factory Method, Abstract Factory) a class used to create other objects www.assignmentpoint.com

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

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)

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

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

Factory sequence diagram

Factory example public 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 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

objects that represent actions Pattern: Command objects that represent actions www.assignmentpoint.com

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

Bad event-handling code public 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?

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

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

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

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

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

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

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

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