The document discusses several design patterns including Iterator, Observer, Strategy, Composite, and Decorator. It provides examples of each pattern and explains the key ideas and benefits of using design patterns, such as allowing reusable and flexible designs that can be communicated through a common vocabulary.
This document discusses design patterns, the observer pattern specifically, and integrated development environments. It describes design patterns as reusable solutions to common problems, and outlines the elements of patterns including their name, problem description, solution description, and consequences. The observer pattern is then explained in detail as a way to separate the display of an object's state from the object itself. The document also briefly discusses tools that are part of integrated development environments like compilers, debuggers, and testing tools.
The document discusses design patterns, including their definition, benefits, common myths, design principles, basic elements, categories, and the pattern life cycle. It provides examples of the Singleton and Observer patterns, and discusses how the Model-View-Controller pattern uses strategies like Observer, Strategy, and Composite. Experts recommend focusing on simplicity, practical extensibility over hypothetical generality, and adapting patterns to problems rather than following them rigidly.
Software development effort reduction with Co-oplbergmans
This talks explains the motivations for the Co-op technology: what are the challenges it addresses, in particular focusing on reducing accidental complexity, where it comes from, and a general vision on how to resolve it. Then we continue to show practical application of Co-op, including experience figures from large-scale application of a previous generation of this technology. Show a little bit about its realization, and conclude with an evaluation of the technology.
This document provides an introduction to design patterns, including their motivation, history, definition, categories, and examples. Some key points:
- Design patterns solve common programming problems by describing reusable solutions that can be adapted for different situations.
- Common categories include creational, structural, and behavioral patterns. Example patterns discussed are Singleton, Decorator, Abstract Factory.
- Design patterns speed up development, promote code reuse, and make software more robust, maintainable and extensible. Resources for further information on design patterns are provided.
This document provides an overview of topics covered in Chapter 7 on software design and implementation, including object-oriented design using UML, design patterns, implementation issues, and open source development. It discusses the design and implementation process, build vs buy approaches, object-oriented design processes involving system models, and key activities like defining system context, identifying objects and interfaces. Specific examples are provided for designing a wilderness weather station system.
Design patterns are commonly used to address problems relating to application architecture and design. The concept originated from Christopher Alexander's work noting common building design problems and solutions. Design patterns ensure problems are addressed through well-known solutions, and most problems have likely been solved before. Common patterns include observer/subject to separate user interface from business logic, singleton to control object construction, strategy to allow multiple algorithms, and template method to define an algorithm's structure. The facade pattern provides different views of subsystems to users by hiding implementation details. The command pattern encapsulates requests as objects with a known interface to decouple senders and receivers.
This document discusses design patterns, the observer pattern specifically, and integrated development environments. It describes design patterns as reusable solutions to common problems, and outlines the elements of patterns including their name, problem description, solution description, and consequences. The observer pattern is then explained in detail as a way to separate the display of an object's state from the object itself. The document also briefly discusses tools that are part of integrated development environments like compilers, debuggers, and testing tools.
The document discusses design patterns, including their definition, benefits, common myths, design principles, basic elements, categories, and the pattern life cycle. It provides examples of the Singleton and Observer patterns, and discusses how the Model-View-Controller pattern uses strategies like Observer, Strategy, and Composite. Experts recommend focusing on simplicity, practical extensibility over hypothetical generality, and adapting patterns to problems rather than following them rigidly.
Software development effort reduction with Co-oplbergmans
This talks explains the motivations for the Co-op technology: what are the challenges it addresses, in particular focusing on reducing accidental complexity, where it comes from, and a general vision on how to resolve it. Then we continue to show practical application of Co-op, including experience figures from large-scale application of a previous generation of this technology. Show a little bit about its realization, and conclude with an evaluation of the technology.
This document provides an introduction to design patterns, including their motivation, history, definition, categories, and examples. Some key points:
- Design patterns solve common programming problems by describing reusable solutions that can be adapted for different situations.
- Common categories include creational, structural, and behavioral patterns. Example patterns discussed are Singleton, Decorator, Abstract Factory.
- Design patterns speed up development, promote code reuse, and make software more robust, maintainable and extensible. Resources for further information on design patterns are provided.
This document provides an overview of topics covered in Chapter 7 on software design and implementation, including object-oriented design using UML, design patterns, implementation issues, and open source development. It discusses the design and implementation process, build vs buy approaches, object-oriented design processes involving system models, and key activities like defining system context, identifying objects and interfaces. Specific examples are provided for designing a wilderness weather station system.
Design patterns are commonly used to address problems relating to application architecture and design. The concept originated from Christopher Alexander's work noting common building design problems and solutions. Design patterns ensure problems are addressed through well-known solutions, and most problems have likely been solved before. Common patterns include observer/subject to separate user interface from business logic, singleton to control object construction, strategy to allow multiple algorithms, and template method to define an algorithm's structure. The facade pattern provides different views of subsystems to users by hiding implementation details. The command pattern encapsulates requests as objects with a known interface to decouple senders and receivers.
The document discusses the design and implementation process in software engineering. It covers topics like using the Unified Modeling Language (UML) for object-oriented design, design patterns, and implementation issues. It then discusses the design process, including identifying system contexts and interactions, architectural design, identifying object classes, and creating design models like subsystem, sequence, and state diagrams. The example of designing a weather station system is used to illustrate these design concepts and activities.
This document discusses the design and implementation chapter of a lecture. It covers topics like using UML for object-oriented design, design patterns, and implementation issues. It then discusses the weather station case study used to illustrate the design process, including defining system context, use cases, architectural design, identifying object classes, design models, and interface specification.
This document discusses design and implementation topics covered in Chapter 7, including object-oriented design using UML, design patterns, implementation issues, and open source development. It provides an example of designing a weather station system using various UML diagrams to illustrate the object-oriented design process. Key activities covered are identifying objects, developing design models, and specifying object interfaces. Implementation issues discussed include reuse, configuration management, and host-target development.
Luis Valencia will give a presentation on applying Typescript design patterns to React/SPFx. He has 17 years of experience including 10 years in SharePoint. The session will focus on writing clean, maintainable code and not flashy user interfaces. It will cover common design patterns like singleton, abstract factory, builder, and factory method. It will also discuss SOLID principles and building shared code libraries. The presentation aims to teach developers how to write code that is easy for others to maintain.
The document discusses various design principles and patterns in Java including the Singleton, Factory Method, Prototype, and Abstract Factory patterns. It provides examples of when and how to apply each pattern, describing their structures, participants, collaborations and consequences. It also covers design principles such as the open-closed principle, dependency inversion, and interface segregation.
This document discusses software design patterns, which provide reusable solutions to common problems in software design. It covers creational patterns like singleton and abstract factory, structural patterns like adapter and bridge, and behavioral patterns like iterator and observer. Patterns help developers solve recurring problems in an elegant and reusable way by providing tried-and-tested solutions to common design problems. The document also discusses categories of patterns, their elements, and when to use different patterns.
This document discusses various design patterns used in Cocoa Touch such as Creational patterns like Prototype, Abstract Factory, Factory Method, and Singleton. Structural patterns covered include Adapter, Facade, Mediator, Observer, Composite, Iterator, and Decorator. Behavioral patterns discussed are Chain of Responsibility, Template Method, Strategy, Command, and more. Examples are provided for how each pattern is implemented in Cocoa Touch frameworks and APIs.
The document discusses several design patterns including Singleton, Observer, Command, Proxy, Facade, Adapter, and Mediator patterns. It provides descriptions of what each pattern is, including examples of how and when to use each pattern. It also discusses the Model-View-Controller pattern and how it is a collection of patterns used to structure user interface applications.
Software Engineering with Objects (M363) Final Revision By Kuwait10Kuwait10
This document provides an overview of software engineering concepts covered in various course units. It begins with introductions to approaches to software development, requirements concepts, and modeling. Key topics covered include the software development life cycle, requirements elicitation and analysis techniques, types of requirements (functional and non-functional), modeling languages like UML, and risks and traceability in software projects. The document also lists contents for each of the 14 course units.
Design and Implementation patterns have changed in object-oriented languages such as C# with the introduction of new language features, advances in object-oriented design, and the inclusion of functional language aspects. This session will explore the impact this has on design and implementation patterns and how they can be leveraged to build more elegant systems.
20090918 Agile Computer Control of a Complex ExperimentJonathan Blakes
The document summarizes a research paper that describes using Python and related tools like Traits and TraitsUI to build a flexible and reliable software system for controlling a complex experiment. It allows for interfacing with specialized hardware, unit testing components, running operations in parallel, building graphical user interfaces, and making the system data-driven and evolvable to change with experimental needs. Key advantages included pushing hardware interface code to a high-level language and automatically generating GUIs based on underlying data models.
The document discusses creating custom components in Android. It explains that custom components can be created by extending the View class and overriding methods like onDraw() and onMeasure(). It provides guidelines for defining custom attributes, applying attributes in code, and adding properties and events to custom components. Creating fully customized components involves extending View, handling drawing and measurement, and responding to user interactions. The document also covers modifying existing widgets by subclassing them and overriding specific methods.
The document discusses three design patterns: Singleton, Observer, and Factory. The Singleton pattern ensures that only one instance of a class can exist and provides a global access point. The Observer pattern defines a subscription mechanism so that multiple objects can be notified of changes to an object they are observing. The Factory pattern provides an interface for creating objects but leaves the concrete class unspecified. Real-world examples and implementations of each pattern are provided.
Lecture 05. UI programming for Mobile AppsMaksym Davydov
This document provides an overview of UI programming for mobile apps. It discusses state machine programming patterns and the model-view-controller (MVC) pattern. It explains how MVC is implemented in Android and iOS. It also describes Android programming basics such as activities, services, content providers, and resources. It covers views, layouts, fragments and other aspects of the Android user interface.
This document discusses various JavaScript design patterns. It begins by defining design patterns as recurring solutions to common software design problems. It then covers types of patterns such as creational, structural, and behavioral. Specific patterns like module, revealing module, singleton, prototype, factory, facade, and observer are demonstrated. Benefits include reusability, communication, and encapsulation. Drawbacks include additional complexity and difficulty testing in some cases. Examples are provided to illustrate usage of the patterns.
The document discusses various software design patterns including Singleton, MVC, Factory Method, and Observer. It provides examples of when and how each pattern is used. For instance, the Singleton pattern ensures only one instance of a resource exists, like a database connection. The MVC pattern separates business logic from presentation logic. The Factory Method creates object instances by defining an interface, while the Observer pattern allows objects to watch others for state changes. Design patterns provide proven solutions to common software problems and facilitate communication between designers.
The document summarizes several design patterns including creational, structural, and behavioral patterns. Creational patterns like abstract factory, builder, and factory method deal with object instantiation. Structural patterns like adapter, bridge, composite deal with class and object composition. Behavioral patterns like chain of responsibility, command, and observer deal with object communication and can be used to implement things like menus, toolbars, and event handling. Many of these patterns are used throughout the .NET framework in various class libraries.
The document discusses the design and implementation process in software engineering. It covers topics like using the Unified Modeling Language (UML) for object-oriented design, design patterns, and implementation issues. It then discusses the design process, including identifying system contexts and interactions, architectural design, identifying object classes, and creating design models like subsystem, sequence, and state diagrams. The example of designing a weather station system is used to illustrate these design concepts and activities.
This document discusses the design and implementation chapter of a lecture. It covers topics like using UML for object-oriented design, design patterns, and implementation issues. It then discusses the weather station case study used to illustrate the design process, including defining system context, use cases, architectural design, identifying object classes, design models, and interface specification.
This document discusses design and implementation topics covered in Chapter 7, including object-oriented design using UML, design patterns, implementation issues, and open source development. It provides an example of designing a weather station system using various UML diagrams to illustrate the object-oriented design process. Key activities covered are identifying objects, developing design models, and specifying object interfaces. Implementation issues discussed include reuse, configuration management, and host-target development.
Luis Valencia will give a presentation on applying Typescript design patterns to React/SPFx. He has 17 years of experience including 10 years in SharePoint. The session will focus on writing clean, maintainable code and not flashy user interfaces. It will cover common design patterns like singleton, abstract factory, builder, and factory method. It will also discuss SOLID principles and building shared code libraries. The presentation aims to teach developers how to write code that is easy for others to maintain.
The document discusses various design principles and patterns in Java including the Singleton, Factory Method, Prototype, and Abstract Factory patterns. It provides examples of when and how to apply each pattern, describing their structures, participants, collaborations and consequences. It also covers design principles such as the open-closed principle, dependency inversion, and interface segregation.
This document discusses software design patterns, which provide reusable solutions to common problems in software design. It covers creational patterns like singleton and abstract factory, structural patterns like adapter and bridge, and behavioral patterns like iterator and observer. Patterns help developers solve recurring problems in an elegant and reusable way by providing tried-and-tested solutions to common design problems. The document also discusses categories of patterns, their elements, and when to use different patterns.
This document discusses various design patterns used in Cocoa Touch such as Creational patterns like Prototype, Abstract Factory, Factory Method, and Singleton. Structural patterns covered include Adapter, Facade, Mediator, Observer, Composite, Iterator, and Decorator. Behavioral patterns discussed are Chain of Responsibility, Template Method, Strategy, Command, and more. Examples are provided for how each pattern is implemented in Cocoa Touch frameworks and APIs.
The document discusses several design patterns including Singleton, Observer, Command, Proxy, Facade, Adapter, and Mediator patterns. It provides descriptions of what each pattern is, including examples of how and when to use each pattern. It also discusses the Model-View-Controller pattern and how it is a collection of patterns used to structure user interface applications.
Software Engineering with Objects (M363) Final Revision By Kuwait10Kuwait10
This document provides an overview of software engineering concepts covered in various course units. It begins with introductions to approaches to software development, requirements concepts, and modeling. Key topics covered include the software development life cycle, requirements elicitation and analysis techniques, types of requirements (functional and non-functional), modeling languages like UML, and risks and traceability in software projects. The document also lists contents for each of the 14 course units.
Design and Implementation patterns have changed in object-oriented languages such as C# with the introduction of new language features, advances in object-oriented design, and the inclusion of functional language aspects. This session will explore the impact this has on design and implementation patterns and how they can be leveraged to build more elegant systems.
20090918 Agile Computer Control of a Complex ExperimentJonathan Blakes
The document summarizes a research paper that describes using Python and related tools like Traits and TraitsUI to build a flexible and reliable software system for controlling a complex experiment. It allows for interfacing with specialized hardware, unit testing components, running operations in parallel, building graphical user interfaces, and making the system data-driven and evolvable to change with experimental needs. Key advantages included pushing hardware interface code to a high-level language and automatically generating GUIs based on underlying data models.
The document discusses creating custom components in Android. It explains that custom components can be created by extending the View class and overriding methods like onDraw() and onMeasure(). It provides guidelines for defining custom attributes, applying attributes in code, and adding properties and events to custom components. Creating fully customized components involves extending View, handling drawing and measurement, and responding to user interactions. The document also covers modifying existing widgets by subclassing them and overriding specific methods.
The document discusses three design patterns: Singleton, Observer, and Factory. The Singleton pattern ensures that only one instance of a class can exist and provides a global access point. The Observer pattern defines a subscription mechanism so that multiple objects can be notified of changes to an object they are observing. The Factory pattern provides an interface for creating objects but leaves the concrete class unspecified. Real-world examples and implementations of each pattern are provided.
Lecture 05. UI programming for Mobile AppsMaksym Davydov
This document provides an overview of UI programming for mobile apps. It discusses state machine programming patterns and the model-view-controller (MVC) pattern. It explains how MVC is implemented in Android and iOS. It also describes Android programming basics such as activities, services, content providers, and resources. It covers views, layouts, fragments and other aspects of the Android user interface.
This document discusses various JavaScript design patterns. It begins by defining design patterns as recurring solutions to common software design problems. It then covers types of patterns such as creational, structural, and behavioral. Specific patterns like module, revealing module, singleton, prototype, factory, facade, and observer are demonstrated. Benefits include reusability, communication, and encapsulation. Drawbacks include additional complexity and difficulty testing in some cases. Examples are provided to illustrate usage of the patterns.
The document discusses various software design patterns including Singleton, MVC, Factory Method, and Observer. It provides examples of when and how each pattern is used. For instance, the Singleton pattern ensures only one instance of a resource exists, like a database connection. The MVC pattern separates business logic from presentation logic. The Factory Method creates object instances by defining an interface, while the Observer pattern allows objects to watch others for state changes. Design patterns provide proven solutions to common software problems and facilitate communication between designers.
The document summarizes several design patterns including creational, structural, and behavioral patterns. Creational patterns like abstract factory, builder, and factory method deal with object instantiation. Structural patterns like adapter, bridge, composite deal with class and object composition. Behavioral patterns like chain of responsibility, command, and observer deal with object communication and can be used to implement things like menus, toolbars, and event handling. Many of these patterns are used throughout the .NET framework in various class libraries.
World trade center in kerala proposal- AR. DEEKSHITH MAROLI 724519251008 REPORTdeekshithmaroli666
World trade center live proposal in kerala.
Future of our nation is looking towards kerala..?
Yes, because the biggest sludge less port is going to open in kerala soon and also about the hidden massing growth of tourism, it , business sector
1. 1
CSE 403
Design Patterns and GUI Programming
Reading:
Object-Oriented Design and Patterns, Ch. 5 (Horstmann)
These lecture slides are copyright (C) Marty Stepp, 2007. They may not be rehosted, sold, or
modified without expressed permission from the author. All rights reserved.
2. 2
Big questions
What is a design pattern?
What is the advantage of knowing/using
design patterns?
Which patterns are named in the reading?
What are the key ideas of those patterns?
3. 3
Design challenges
Designing software for reuse is hard. One must find:
a good problem decomposition, and the right software
a design with flexibility, modularity and elegance
designs often emerge from trial and error
successful designs do exist
two designs they are almost never identical
they exhibit some recurring characteristics
Can designs be described, codified or standardized?
this would short circuit the trial and error phase
produce "better" software faster
4. 4
Design patterns
design pattern:
a solution to a common software problem in a context
describes a recurring software structure
is abstract from programming language
identifies classes and their roles in the solution to a problem
patterns are not code or designs; must be instantiated/applied
example: Iterator pattern
The Iterator pattern defines an interface that declares methods
for sequentially accessing the objects in a collection.
5. 5
History of patterns
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
1995 book Design Patterns:
Elements of Reusable Object-Oriented
Software is a classic of the field
6. 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)
7. 7
Gang of Four (GoF) patterns
Creational Patterns
(abstracting the object-instantiation process)
Factory Method Abstract Factory Singleton
Builder Prototype
Structural Patterns
(how objects/classes can be combined to form larger structures)
Adapter Bridge Composite
Decorator Facade Flyweight
Proxy
Behavioral Patterns
(communication between objects)
Command Interpreter Iterator
Mediator Observer State
Strategy Chain of Responsibility Visitor
Template Method
9. 9
Iterator pattern
iterator: an object that provides a standard way to
examine all elements of any collection
uniform interface for traversing many different data structures
supports concurrent iteration and element removal
for (Iterator<Account> itr = list.iterator(); itr.hasNext(); ) {
Account a = itr.next();
System.out.println(a);
}
set.iterator()
map.keySet().iterator()
map.values().iterator()
11. 11
Recall: model and view
model: classes in your system that are related to the
internal representation of the state of the system
often part of the model is connected to file(s) or database(s)
examples (card game): Card, Deck, Player
examples (bank system): Account, User, UserList
view: classes in your system that display the state of
the model to the user
generally, this is your GUI (could also be a text UI)
should not contain crucial application data
Different views can represent the same data in different ways
Example: Bar chart vs. pie chart
examples: PokerPanel, BankApplet
12. 12
Model-view-controller
model-view-controller (MVC): common design
paradigm for graphical systems
controller: classes that connect model and view
defines how user interface reacts to user input (events)
receives messages from view (where events come from)
sends messages to model (tells what data to display)
sometimes part of view (see left)
Model
Controller
View
data for
rendering
events
updates
Model
View
Component
Controller
13. 13
Observer pattern
observer: an object that "watches" the state of
another object and takes action when the state
changes in some way
examples in Java: event listeners; java.util.Observer
observable object: an object that allows observers to
examine it (often the observable object notifies the
observers when it changes)
permits customizable, extensible event-based behavior for data
modeling and graphics
14. 14
Benefits of observer
abstract coupling between subject and observer; each
can be extended and reused individually
dynamic relationship between subject and observer;
can be established at run time (can "hot-swap" views,
etc) gives a lot more programming flexibility
broadcast communication: notification is broadcast
automatically to all interested objects that subscribed
to it
Observer can be used to implement model-view
separation in Java more easily
16. 16
Observer interface
package java.util;
public interface Observer {
public void update(Observable o, Object arg);
}
Idea: The update method will be called when the
observable model changes, so put the appropriate code
to handle the change inside update
17. 17
Observable class
public void addObserver(Observer o)
public void deleteObserver(Observer o)
Adds/removes o to/from the list of objects that will be notified (via their
update method) when notifyObservers is called.
public void notifyObservers()
public void notifyObservers(Object arg)
Inform all observers listening to this Observable object of an event that
has occurred. An optional object argument may be passed to provide
more information about the event.
public void setChanged()
Flags the observable object as having changed since the last event; must
be called each time before calling notifyObservers.
18. 18
Common usage of Observer
1. write a model class that extends Observable
have the model notify its observers when anything significant
happens
2. make all views of that model (e.g. GUI panels that
draw the model on screen) into observers
have the panels take action when the model notifies them of
events (e.g. repaint, play sound, show option dialog, etc.)
19. 19
make an Observable model
write a View interface or abstract class
make View an observer
extend/implement View for all actual views
give each its own unique inner components and code to draw
the model's state in its own way
provide mechanism in GUI to set view (perhaps
through menus)
to set view, attach it to observe the model
Using multiple views
20. 20
// in the frame's action listener:
// hide old view; show new one
model.deleteObserver(view1);
model.addObserver(view2);
view1.setVisible(false);
view2.setVisible(true);
Example: changing views
22. 22
strategy: an algorithm separated from the object that
uses it, and encapsulated as its own object
each strategy implements one behavior, one implementation of
how to solve the same problem
separates algorithm for behavior from object that wants to act
allows changing an object's behavior dynamically without
extending / changing the object itself
examples:
file saving/compression
layout managers on GUI containers
AI algorithms for computer game players
Strategy pattern
23. 23
Strategy example: Card player
// Strategy hierarchy parent
// (an interface or abstract class)
public interface Strategy {
public Card getMove();
}
// setting a strategy
player1.setStrategy(new SmartStrategy());
// using a strategy
Card p1move = player1.move(); // uses strategy
24. 24
The idea: Place many components into a special component called
a container, then add the container to the window frame
Containers with layout
25. 25
Container
container: an object that holds components; it also
governs their positions, sizes, and resize behavior
public void add(Component comp)
public void add(Component comp, Object info)
Adds a component to the container, possibly giving
extra information about where to place it.
public void remove(Component comp)
Removes the given component from the container.
public void setLayout(LayoutManager mgr)
Uses the given layout manager to position the
components in the container.
public void validate()
You should call this if you change the contents of a
container that is already on the screen, to make it re-
do its layout.
27. 27
Composite pattern
composite: an object that is either an individual item
or a collection of many items
composite objects can be composed of individual items or of
other composites
recursive definition: objects that can hold themselves
often leads to a tree structure of leaves and nodes:
<node> ::= <leafnode> | <compositenode>
<compositenode> ::= <node>*
examples in Java:
collections (a List of Lists)
GUI layout (panels containing panels containing buttons, etc.)
28. 28
Composite example: panels
Container north = new JPanel(new FlowLayout());
north.add(new JButton("Button 1"));
north.add(new JButton("Button 2"));
Container south = new JPanel(new BorderLayout());
south.add(new JLabel("Southwest"), BorderLayout.WEST);
south.add(new JLabel("Southeast"), BorderLayout.EAST);
// overall panel contains the smaller panels (composite)
JPanel overall = new JPanel(new BorderLayout());
overall.add(north, BorderLayout.NORTH);
overall.add(new JButton("Center Button"), BorderLayout.CENTER);
overall.add(south, BorderLayout.SOUTH);
frame.add(overall);
30. 30
Decorator pattern
decorator: an object that modifies behavior of, or
adds features to, another object
decorator must maintain the common interface of the object it
wraps up
used so that we can add features to an existing simple object
without needing to disrupt the interface that client code expects
when using the simple object
the object being "decorated" usually does not explicitly know
about the decorator
examples in Java:
multilayered input streams adding useful I/O methods
adding scroll bars to GUI controls
31. 31
Decorator example: I/O
normal InputStream class has only public int
read() method to read one letter at a time
decorators such as BufferedReader or Scanner add
additional functionality to read the stream more easily
// InputStreamReader/BufferedReader decorate InputStream
InputStream in = new FileInputStream("hardcode.txt");
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
// because of decorator streams, I can read an
// entire line from the file in one call
// (InputStream only provides public int read() )
String wholeLine = br.readLine();
32. 32
Decorator example: GUI
normal GUI components don't have scroll bars
JScrollPane is a container with scroll bars to which you
can add any component to make it scrollable
// JScrollPane decorates GUI components
JTextArea area = new JTextArea(20, 30);
JScrollPane scrollPane = new JScrollPane(area);
contentPane.add(scrollPane);
JComponents also have a setBorder method to add a
"decorative" border. Is this another example of the Decorator
pattern? Why or why not?
33. 33
References
The Java Tutorial: Visual Index to the Swing Components.
http://java.sun.com/docs/books/tutorial/
uiswing/components/components.html
The Java Tutorial: Laying Out Components Within a Container.
http://java.sun.com/docs/books/tutorial/uiswing/
layout/index.html
Java Class Library Reference: Observer, Observable.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Observer.html
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Observable.html
Cunningham & Cunningham OO Consultancy, Inc.
http://c2.com/cgi/wiki?IteratorPattern
http://c2.com/cgi/wiki?DecoratorPattern
http://c2.com/cgi/wiki?CompositePattern
Design Patterns Java Companion
http://www.patterndepot.com/put/8/JavaPatterns.htm