DP
DP
1. Fundamental Design Patterns are general concepts, they are needed in most other
patterns to accomplish their task.
A. Interface
B. Container
C. Delegation
2. Architectural Patterns express a fundamental structural organization or schema for
software systems. They provide a set of predefined subsystems, specify their
responsibilities, and include rules and guidelines for organizing the relationships
between them.
Architectural Patterns
Architectural patterns borrow a lot of terminology and concepts from design patterns, but
focus on providing re-usable models and methods specifically for the over-all architecture of
information systems. This means they are not complete templates like other "design"
patterns that can be directly applied to code. Architectural patterns comprise software,
hardware, networks, and people as opposed to pure source code.
Model View Controller is one of the oldest patterns (SmallTalk-80) and thus very
fundamental to software development. MVC separates the concerns regarding data
(model) and user interface (view) so that changes to the user interface do not
impact the data handling and the data can be reorganized without changing the user
interface.
Interface is a special type of class which provides the programmer with a simpler or
more program-specific way of accessing other classes. Since the Java programming
language relies on its interfaces to expose the functionality of a class to the outside
world, it is an integral part of the language (unlike C++, which has header files).
However the "interface pattern" discussed here is a even more general term without
the restrictions placed upon interfaces by Java, for example the delegation,
composite and bridge patterns are different types of interface patterns, however they
do also have an implementation, so they would not conform to what Java calls an
interface.
Container - called collection in Java - is an object that groups multiple elements into
a single unit. Containers are used to store, retrieve, manipulate, and communicate
aggregate data. Examples of collection implementations in Java include Vector and
Hashtable.
Data Access Object abstracts and encapsulates all access to a data source letting
the implementation underneath vary while presenting a uniform interface to your
program.
Transfer Object encapsulates all the data associated with a specific type of entity,
for a example a book, date, or bank account. It helps reduce the amount of method
calls and makes the actual method call much nicer to read.
flexibility of object composition comes from the ability to change the composition at runtime.
Facade shows how to make a single object represent an entire subsystem. It carries
out its responsibility by forwarding messages to the objects it represents.
This really leads to hard coding how you create the object within your program. In many
cases, the exact nature of the object that is created could vary with the needs of your
program. Abstracting the creation process into a special "creator" class can make your
program more flexible and general.
A class creational pattern uses inheritance to vary the class that's instantiated. [GoF,
"Design Patterns", Addison Wesley, ISBN 0201633612]. The main drawback of this
approach is that it can require creating a new subclass just to change the class of the
product. Such changes can cascade. For example, when the product creator is itself created
by a factory method, then you have to override its creator as well.
Factory Method defines an interface for creating an object, but lets subclasses
decide which class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
Object Pool manages and creates instances of a class that can be used
interchangeably. These created objects could be expensive to create or maybe only a
limited number of one kind of object should be created - the Object Pool manages
these objects also after they are instantiated unlike the Factory patterns. The Object
Pool pattern, when used in the right place, can result in a dramatic improvement in
speed while lowering memory requirements.
An object creational pattern will delegate instantiation to another object which is responsible
for knowing the class of the product objects, and it will make it a parameter of the
system. [GoF, "Design Patterns", Addison Wesley, ISBN 0201633612]. They involve creating
a new "factory object" whose responsibility is to create product objects.
Singleton ensures a class has only one instance at all times and provides one global
point of access to it.
Behavioral class patterns use inheritance to distribute behavior between classes. [GoF,
"Design Patterns", Addison Wesley, ISBN 0201633612].
Behavioral object patterns use object composition rather than inheritance. [GoF, "Design
Patterns", Addison Wesley, ISBN 0201633612].
Iterator encapsulates the way you access and traverse the elements of an
aggregate sequentially without exposing its underlying representation.
Pattern Map
The diagram below shows the relationships between the patterns described, notation
according to Zimmer's classifications and relationships. [Zimmer, Walter (1995),
"Relationships between Design Patterns", from "Pattern Languages of Program Design",
Addison-Wesley.]
There are three types of relationships in this diagram:
1. uses (pattern us used by)
2. combine (pattern can be used by)
3. similar (patterns are similar in their design).
Interface Pattern
An interface defines the signature operations of an entity, it also sets the communication
boundary between two entities, in this case two pieces of software. It generally refers to an
abstraction that an asset provides of itself to the outside.
The main idea of an interface is to separate functions from implementations. Any request
that matches the signature or interface of an object may also be sent to that object,
regardless of its implementation.
Since it does not matter which implementation of a specific class is used, a class can be
exchanged easily without changing the code of the calling class.
The concept of an interface is fundamental in most object oriented programming languages.
In some, objects are known only through their interfaces so there is no way to access an
object without going through it's interface.
Applicability / Uses
Use an interface when:
you want to specify how classes exchange messages. I.e., every time, when a class
should be reused, or used outside a specific context (package) declare the
communication interface as an Interface type
at design-time you don't yet know which implementation you will use at compile-time
Related Patterns
Many other patterns use interfaces, a lot of them depend on the interface pattern.
It is possible to combine the interface pattern with virtually any other pattern to
make them more flexible.
Structure
Sample
This example uses an interface for sending messages across the system. The
interface defines a single method to send a message:
public interface Messenger {
public void sendMessage(String receiver, String text);
}
Notice, that in the Sender-class we didn't know how the message will be
sent. In this case it was sent via mail, but it could also just be printed to
stdout:
public class StdOutMessenger implements Messenger {
public void sendMessage(String receiver, String text) {
// Just print to stdout
System.out.println("A message is sent to " + receiver + ":");
System.out.println(text);
}
}
Such a construction of using an interface is often combined with the FactoryPattern to retrieve the Implementation of the interface.
Container Pattern
A Container is an object created to hold other objects that are accessed, placed, and
maintained with the class methods of the container - queues, sets, lists, vectors, and caches
all fit this description. These objects - the elements of the container - are usually allowed to
be of any class and may be of the container class itself. Every Container should also have an
associated Iterator type that can be used to iterate through the elements of the container.
The term container in modern computer programming can actually refer to many things:
Java programmers tend to call these types of classes "collections" rather than
"containers". The Java Collections Framework provides implementations for many
kinds of container classes, a typical implementation of a collection class in Java
would be ArrayList or Hashtable.
Within the Spring Framework containers represent much more higher level concepts
such as inversion of control (IoC). See dependency injection for a sample
implementation of IoC.
Enterprise beans are software components that run in a special environment called
an EJB container. The container hosts and manages an enterprise bean in the same
manner that the Java Web Server hosts a servlet or an HTML browser hosts a Java
applet.
Applicability / Uses
Use a Container Pattern when:
Related Patterns
Structure
This class diagram shows a simple Container which implements only the
add(E o) and iterator() methods. To be really useful you would of course also
implement methods like remove(E o), contains(E o), isEmpty(), size(), etc...
Sample
A Container Pattern should really make use of the Interface Pattern, in our
short example here we won't implement an interface because we want to
concentrate on how a container works. Please note that if you need to create
your own container, which is very rare anyway since the Java Collections
Framework is quite good, you should implement the Collection interface
(public class MyContainer<E> implements Collection<E>) in order to make
your container compatible with the Java Collections Framework.
public class MyContainer<E> {
protected class Node {
private E element;
Node next = null;
Node previous = null;
string_cont.add("one");
string_cont.add("two");
string_cont.add("three");
Iterator<String> string_it = string_cont.iterator();
while (string_it.hasNext()) {
System.out.println("String Container: " +
string_it.next());
}
// Container Container
MyContainer<MyContainer<Integer>> cont_cont =
new MyContainer<MyContainer<Integer>>();
cont_cont.add(int_cont);
// cont_cont.add(string_cont); This does not work ->
MyContainer<Integer> !
Iterator<MyContainer<Integer>> cont_it = cont_cont.iterator();
while (cont_it.hasNext()) {
MyContainer<Integer> it = cont_it.next();
Iterator<Integer> it_it = it.iterator();
while (it_it.hasNext()) {
System.out
.println("Integer Container inside
Container Container: "
+
it_it.next());
}
}
}
Delegation Pattern
"Delegation is like inheritance done manually through object
composition." [Lecture slides of course 601: "Object-Oriented Software Development" at
the University of San Francisco ]
It is a technique where an object expresses certain behavior to the outside but in reality
delegates responsibility for implementing that behaviour to an associated object. This
sounds at first very similar to the proxy pattern, but it serves a much different purpose.
Delegation is an abstraction mechanism which centralizes object (method) behaviour.
The diagram above shows how multiple-inheritance behavior can be accomplished in Java
for actual classes. Of course delegation is not limited to scenarios where multipleinheritance has to be avoided (as Java does not support this), but can be seen in general as
an alternative to inheritance. The same functionality can also be accomplished with
interfaces, however sometimes the relationship you want between two classes is actually
one of containment rather than inheritance.
Applicability / Uses
Use the delegation pattern when:
you have components that behave identically, but realize that this situation can
change in the future.
This pattern is also known as "proxy chains". Several other design patterns
use delegation - the State, Strategy and Visitor Patterns depend on it.
Related Patterns
Structure
This example is actually more advanced than just plain delegation, it shows
how delegation makes it easy to compose behaviors at run-time.
Sample
First lets create an Interface for our Delegates, since Delegates can be
interchanged they all must implement the same interface:
public interface ISoundBehaviour {
}
Now lets create a cat class which uses the MeowSound per default:
public class Cat {
private ISoundBehaviour sound = new MeowSound();
public void makeSound() {
this.sound.makeSound();
}
MVC proposes three types of objects in an application, the Model, Views and Controllers.
These objects are separated by abstract boundaries which makes MVC more of a paradigm
rather than an actual pattern since the communication with each other across those
boundaries is not further specified. How the objects inside MVC communicate differs not
only by the type of application you are describing (GUI, web) but also by which part of the
application you are currently looking at (frontend, backend).
However, at the heart of every MVC architecture lies Separated Presentation which
declares a clear division between domain objects that model our perception of the real world
(model objects), and presentation objects that are the GUI elements we see on the screen
(view objects).
MVC defines the separation of these three types of objects:
1. Model objects hold data and define the logic for manipulating that data. For
example, a Student object in the Basic sample application is a model object. It holds
data describing facts about the object like the first and last name of the student and
has methods that can access and change this data (getters & setters). Model objects
are not directly displayed. They often are reusable, distributed, persistent and
portable to a variety of platforms.
2. View objects represent something visible in the user interface, for example a panel
or button. In order to display the data from the model objects you might want to
create your own custom objects, like a graph for example.
3. The Controller object acts as a Mediator between the Model and View objects. A
Controller object communicates data back and forth between the Model objects and
the View objects. For example a controller could mediate the first name of a student
from a model object to a visible text field in the User Interface. A controller also
performs all application specific tasks, such as processing user input or loading
configuration data. There is usually one controller per application or window, in many
applications the Controller is tightly coupled to the view. The Basic sample
application shows this - every GUI class implements its own ActionListeners. Since
controllers are application specific they usually do not find any reuse in other
applications.
Designing your application strictly according to MVC is not always advisable. If you are
designing a graphics intensive program, like a game, you would probably couple the View
and Model classes much more tightly than what MVC suggests. As we can see from the
Basic sample application, when programming a very simple application it is common to
combine the controller with the view classes.
Also, the MVC paradigm is not necessarily specific to Object Oriented programming
languages. For example, an application written in PHP4 while not being Object-Oriented, can
also follow the principles of the Model View Controller pattern using templating systems or
MVC frameworks designed for PHP.
Applicability / Uses
This pattern should be used:
Related Patterns
The Model-View-Controller paradigm uses different patterns depending on
what kind of application you are designing. It is common to find things like
Intercepting Filters, View Helpers, Composite Views, Front Controllers, Value
Objects, Session facades, Business Delegates and Data Access Objects used
by the MVC architectural pattern, here are a few of the most heavily used
ones:
Observer: used by Model and View. When the information stored in the Model classes
changes, the View classes need to be notified and updated with the latest
information. In order to retain loose coupling between these Model/View and also
due to the fact that there can be several Views instantiated, the Observer pattern is
a perfect candidate to accomplish this.
Strategy: used by the Model. The Data Access Object pattern is a form of the
strategy pattern it is used primarily by the Model to access different form of datasources. For example a MySQL/Postgres Database and XML files stored on the
filesystem.
Composite: used by the View. There can be several different views within a system
designed according to MVC, in order for these different implementations to be
composed together and exchanged at run time, the composite pattern is used.
Dependency Injection
One of the main goals of decomposing complex problems into smaller modules and
implementing these modules are dependencies. A module that relies heavily on a underlying
technology or platform is less reusable and makes changes to software complex and
expensive.
The Dependency Injection pattern is used in almost every framework and is based on the
"inversion of control" (IoC) principle. It relates to the way in which an object obtains
references to its dependencies - the object is passed its dependencies through constructor
arguments or after construction through setter methods or interface methods. It is called
dependency injection since the dependencies of an object are 'injected' into it, the term
dependency is a little misleading here, since it is not a new 'dependency' which is injected
but rather a 'provider' of that particular capability. For example, passing a database
connection as an argument to a constructor instead of creating one internal would be
categorized as dependency injection.
The pattern seeks to establish a level of abstraction via a public interface and to remove
dependencies on components by supplying a 'plugin' architecture. This means that the
individual components are tied together by the architecture rather than being linked
together themselves. The responsibility for object creation and linking is removed from the
objects themselves and moved to a factory.
There are 3 forms of dependency injection: setter-, constructor- and interface-based
injection. We will concentrate on setter-based injection here since that is the recommended
methodology using the Spring Framework. To get rid of dependencies, Spring uses the idea
of dependency injection.
When developing - for example - a business service, that service is implemented to work
with an interface of the Data Access Object. If you then want to use that module with a
certain DAO - for example a DAO to access your mySQL database - you somehow have to
tell the service to use exactly that object. This, however, would create a dependency
between the service and the DAO. With the IoC pattern, as implemented in Spring, the
developer defines which DAO (in this case the mySQL DAO) in an external configuration file
(in our example: beans.xml). At runtime, the information from the configuration file are
parsed and the dependency is injected into the service.
The sample uses dependency injection for multiple tasks:
for DAOs
for DataSources
The test class JdbcStudentTest can show you a simple example of dependency injection in
action. If you understand what is going one, have a look at the JdbcObjectStudentDAO.
More flexibility is obtained especially for testing since dependencies on a particular
deployment environment can be removed from the code making it much easier to test
functionality in a simple stand-alone environment. Especially when using mock-objects this
technique results in highly testable objects. Avoiding dependencies of collaborating classes
makes it possible to produce controlled unit-tests that focus on exercising the behaviour of
only the class undergoing the test. To achieve this, dependency injection is used to cause
instances of the class under the test to interact with mock objects.
Applicability / Uses
Use the dependency injection pattern when:
you are expecting to run controlled unit tests. With dependency injection, testing can
begin very early in the development cycle
you want to save time in that you don't have to write boilerplate factory creation
code over and over again
Related Patterns
Structure
UML class diagram of the sample code:
Sample
First we implement the Movie entity which will be searching for:
public class Movie {
private String director;
...
public Movie(String director, ...) {
this.director = director;
...
}
public String getDirector() {
return director;
}
}
...
Now lets look at a component which finds all movies which where directed by
one particular director, this is done by a single method. When we talk about
this class we shall assume it is a component - a piece of software intended
to be used, without change, by an application that is out of control of the
writers of the component. And by 'without change' we mean no changes to
the source code of the component. However we will of course provide a
mechanism for altering the behaviour of our Movies class, this is where
dependency injection comes into play:
At some point we will have to introduce a concrete class for actually finding
all the movies, we will put this code into the constructor of the Movies class:
public class Movies {
private MovieFinder finder;
public Movies() {
this.finder = new SemiColonDelimitedMovieFinder("movies.txt");
}
And lastly we then test the code we have written so far to demonstrate
dependency injection through a Spring container.
public void testWithSpring() throws Exception {
ApplicationContext ctx = new
FileSystemXmlApplicationContext("spring.xml");
MovieLister lister = (MovieLister) ctx.getBean("MovieLister");
Movie[] movies = lister.moviesDirectedBy("Sergio Leone");
assertEquals("Once Upon a Time in the West", movies[0].getTitle());
}
Decorator Pattern
A decorator object allows you to add new behaviour to other objects at runtime. You can
also think of this in terms of graphical interface components where a decorator object
contains a border or shadow which it uses to actually visually decorate another graphical
component. However a decorator can also add new functionality to existing components,
like scrolling and zooming. It is a good alternative to subclassing (inheritance) which allows
you to create child objects with a new behaviour during implementation. Subclassing
extends an entire class hierarchy, decoration allows the transparent extension
of particular objects at runtime. This also means that you don't have to subclass several
times for the same functionality - you can add one decorator (one "functionality" or
"behaviour") to many objects.
To achieve this, a Decorator must maintain the same interface as the object it "decorates"
and it must accept the object it is "decorating" as an argument in its constructor. It keeps
this original object in a private member variable.
The advantage of using the decorator pattern becomes quite clear when you are confronted
with a large number of independent ways to extend functionality, especially when you can't
predict at design time which combinations of extensions will be used during runtime. You
can decorate a decorator object by simply nesting them within each other since they all
conform to the same interface and forward their messages to the next decorator or original
object.
The Decorator pattern is also known as "Wrapper". It provides its functionality by wrapping
itself around the original object.
Applicability / Uses
Use the decorator pattern to:
Structure
UML diagram of a standard Decorator pattern (GoF):
Sample
This sample code is based on [Budi Kurniawan, "Using the Decorator
Pattern", ONJava.com].
We will try to show the relevance of the Decorator pattern using a real-world
example which is also the most widely used example for this pattern - Java
Swing components. In this example, our decorator will actually visually
decorate other Swing Components, however keep in mind that decorators
can also be used to add new functionality rather than just a new look, which
is what the word decoration implies.
First lets take a look at the JComponent class, this class has a lot more
methods than shown in this code, we are only looking at the bare minimum
amount of methods necessary to explain decoration.
public abstract class JComponent
extends Container
implements Serializable {
...
public JComponent() {
...
}
public void paint (Graphics g) {
// Invoked by Swing to draw this component
// and its children on the screen
}
...
}
Now lets create our decorator, it inherits directly from the JComponent class,
which means it will also inherit the implementation of JComponent's
serializable interface as well as JComponent's implementation of the abstract
methods defined in the Container class.
public class BorderDecorator extends JComponent {
protected JComponent component;
public BorderDecorator(JComponent c){
this.component = c;
this.setLayout(new BorderLayout());
this.add(component);
}
public void paint(Graphics g) {
super.paint(g);
int height = this.getHeight();
int width = this.getWidth();
g.drawRect(0, 0, width-1, height-1);
}
}
Notice that the constructor of BorderDecorator adds the parameter "c" which
is a JComponent as a child to the component of the decorator. Since we are
also using the BorderLayout, this child element will occupy the entire area of
the decorator.
Also notice the modified paint method, it first calls the paint method of the
parent class, after this our decorator draws a border around it, after first
establishing height and width of the element.
Facade Pattern
A common design goal is to minimize the communication and dependencies between
subsystems. [GoF, "Design Patterns"]
As you can see from the simplified diagram below the facade pattern is one way to achieve
this, it provides a unified class which reduces communication between the complex
subsystem and its clients. Clients do not have to be aware of the actual implementation of
the subsystem and are provided with a simpler interface to this subsystem.
Applicability / Uses
Use the facade pattern when:
you want to layer your subsystems. Use a facade to define an entry point to each
subsystem level and make them communicate only through their facades, this can
simplify the dependencies between them.
Related Patterns
Abstract Factory can be used with Facade to provide an interface for creating
subsystem objects.
Facades are often implemented as Singletons when only one facade per subsystem is
needed/desired.
Facade is very similar to Adapter, they are both wrappers and while you will often
find facades wrapping multiple objects and adapters wrapping single objects, keep in
mind this is not the difference between them.
Structure
The sample code is based on the JavaWorld Article "Facade clears
complexity", by David Geary, 05/30/03. We will be taking a look at the class
javax.swing.JOptionPane, which is a Facade class, it provides a simple
interface to different Dialogs (Confirm, Input, Message and OptionDialogs) of
the Java Swing subsystem.
Sample
First lets look at how to create our own Dialog box without the use of
JOptionPane:
...
JFrame frame = new JFrame("My Message Dialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Quit");
JLabel label = new JLabel("This is My Message Dialog!");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.exit(0);
}
};
button.addActionListener(actionListener);
The code above creates a new JFrame and adds a new JButton and JLabel
object to its ContentPane. It also defines an Actionlistener for the Exit
button. Please note that we have not done any visual improvements here
except use the default BorderLayout from JFrame's ContentPane. When the
above code is compiled and run, the JFrame looks like this:
Now lets take a look at doing this with the help of the JOptionPane Facade
class. The same goal as above is accomplished - a pop-up Message Dialog
box, however this time with better visual formatting, some eyecandy and
less lines of code:
...
JOptionPane optionPane = new JOptionPane(
"This Dialog is generated by the JOptionPane Facade!",
JOptionPane.OK_OPTION);
JDialog dialog = optionPane.createDialog(frame.getContentPane(),
"JOptionPane Message Dialog");
dialog.setVisible(true);
...
Alternatively, you can also use the static method provided by JOptionPane to
create the Message Dialog:
...
JOptionPane.showMessageDialog(frame.getContentPane,
"JOptionPane Message Dialog",
"Error!", JOptionPane.ERROR_MESSAGE);
...
As you can see, the JOptionPane Facade in Java Swing provides an easy
interface to programmers who simply want to create a pop-up Message
Dialog.
Proxy Pattern
The intent of the proxy-pattern is to provide a placeholder for another object to control
access to it. It introduces an additional level of indirection. There are several reasons why
you would want to do this, hence there are several uses for this pattern.
One reason for controlling access to an object is to defer the full cost of its creation and
initialization until we actually need to use it. Consider a document editor that can embed
graphical objects in a document. It isn't necessary to load all pictures when the document is
opened, because not all of these objects will be visible at the same time
So we could think about loading each picture on demand, which occurs when an image
becomes visible in the document. But what do we put in the document instead of the
image? And how can we hide that the pictures are created on demand?
The solution is to use another object, a proxy, in place of an image. The proxy acts like an
image and loads the picture when it's required.
The proxy loads and creates the real image just when the document editor requests for
showing that image by invoking its draw-method. The proxy then loads the image and
forwards the request to it.
This was one usage of a proxy, but there are many more. Some have their own names,
depending on their responsibility:
A remote proxy is responsible for encoding a request and its arguments and for
sending (and retrieving) the request (and the response) to the real object.
A virtual proxy may cache additional information about the real subject so that it
can postpone the access to it.
A protection proxy checks whether the caller has sufficient access permissions for
perform a request.
In many cases, real world proxies are a combination of some of these basic proxies.
Applicability / Uses
The proxy pattern is applicable whenever there is a need for a more versatile
or sophisticated reference to an object than just a simple pointer.
Related Patterns
Usually proxies use some form of the facade pattern to supply a unified interface.
It is similar to the decorator pattern which might be a more specific case of the use
of a proxy.
Structure
Sample
In this short example we will use a virtual proxy to handle images.
At first, we need a common interface for a graphic:
public interface Graphic {
And now at last, we create the proxy class. The ImageProxy object will
maintain references to the real Image object. The interfaces of Image and
ImageProxy are identical, however their implementations are of course
different. This proxy class may also be responsible for the creation of the
Image object or it may also fulfill additional tasks like caching the extent of
the image.
public class ImageProxy implements Graphic {
// Variables to hold the concrete image
private String filename;
private Image content;
public ImageProxy(String filename) {
this.filename = filename;
content = null;
}
// on a draw-request, load the concrete image
//
if we haven't done it until yet.
public void draw() {
if (content == null) {
content = new Image(filename);
}
// Forward to the Concrete image.
content.draw();
Applicability / Uses
Use a Data Access Object when:
you need to access a persistent storage more than one time, especially if you want to
exchange the data source later.
you want to separate a data resource's client interface from its data access
mechanisms
you want to adapt a specific data resource's access API to a generic client interface
in a larger project, different teams work on different parts of the application: the
DAO pattern allows clean separation of concerns.
Related Patterns
Abstract Factory: Applications often use a Factory to select the right DAO
implementation at run time.
Transfer Object: The DAO pattern often uses a Transfer Object to send data from the
data source to its client and vice versa.
Structure
UML diagram of the sample code:
Sample
In the following example we will create a Data Access Object for
saving/retrieving the data of books.
To keep the source-code simple, import declarations and exception-handling
is not shown.
public interface BookDAO {
The first implementation flavor will use a simple database (possibly remote)
for storing the data:
public class DBBookDAO implements BookDAO {
private PreparedStatement saveStmt;
private PreparedStatement loadStmt;
public DBBookDAO(String url, String user, String pw) {
Connection con = DriverManager.getConnection(url, user, pw);
saveStmt = con.prepareStatement("INSERT INTO books(isbn, title, author) "
+"VALUES (?, ?, ?)");
loadStmt = con.prepareStatement("SELECT isbn, title, author FROM books "
+"WHERE isbn = ?");
}
public Book loadBook(String isbn) {
Book b = new Book();
loadStmt.setString(1, isbn);
ResultSet result = loadStmt.executeQuery();
if (!result.next()) return null;
b.setIsbn(result.getString("isbn"));
b.setTitle(result.getString("title"));
b.setAuthor(result.getString("author"));
return b;
The second implementation flavor saves every book in its own text-file on
the local hard drive:
public class FileBookDAO implements BookDAO {
private String basePath;
public FileBookDAO(String basePath) {
this.basePath = basePath;
}
public Book loadBook(String isbn) {
FileReader fr = new FileReader(basePath + isbn);
BufferedReader br = new BufferedReader(fr);
Book b = new Book();
String rIsbn = br.readLine();
if (rIsbn.startsWith("ISBN: ")) {
b.setIsbn(rIsbn.substring("ISBN: ".length()));
} else {
return null;
}
if (rTitle.startsWith("TITLE: ")) {
b.setTitle(rTitle.substring("TITLE: ".length()));
} else {
return null;
}
if (rAuthor.startsWith("AUTHOR: ")) {
b.setAuthor(rAuthor.substring("AUTHOR: ".length()));
} else {
return null;
}
return b;
Transfer Object
Remember the Example from the Data Access Object pattern, where we used to send
information about books from one object to another. In case just using built-in data-types
(such as String, int, ...) a call tosaveBook would look like
dao.saveBook("123456789X", "A Book of Books", "Martha T. Bone");
Now imagine we want to save more information than just isbn, title and author. We could
add publisher, price, coverimage, release-date, and even more. The method-call would
become rather unreadable.
Furthermore think about a method returning data of a book. Through it is not possible in
Java to return more than one value, you would have to make several calls to get all data.
The solution for this problem is the Transfer Object. A Transfer Object is an object
encapsulating data. A single method call is now sufficient to send and retrieve the Transfer
Object and all included data.
Applicability / Uses
Use the Transfer Object pattern when:
the number of calls made by a client to a Data Access Object or Enterprise Bean
impacts network performance
you want to reduce communication effort when dealing with a lot of small data
entities
Related Patterns
Data Access Object: A Transfer Object pattern is often used in combination with a
Data Access Object pattern.
Structure
UML diagram of the sample code:
Sample
In this example we consider an advanced Book.
public class Book {
private String isbn;
private String title;
private String author;
private String publisher;
private float price;
private int pages;
private Date releaseDate;
private byte[] coverImage;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
Singleton Pattern
In many cases, it is important for some classes having at most one Instance. There might
exist many printers in the system, but there should be only one printer spooler.
But how can we ensure, that there is only one Instance and that this instance is easily
accessible? A global variable would make the Instance accessible, but it can't keep you from
instantiating more than on object.
A better solution is to make the class itself responsible for watching over its status and its
sole instance. The class can ensure that only one instance is created by hiding the
constructors, and it can provide a way to access the instance. This is called the Singleton
pattern, it consists of just one class, all methods which provide a way to access the instance
are usually static.
Applicability / Uses
You should use the Singleton pattern when
there must be exactly one instance of a class, and it must be accessible for many
clients via a known access point.
the sole instance should be extensible by subclassing, hence clients should be able to
use an extended instance without changes in their code.
Related Patterns
Facade, Abstract Factory, and Object Pool usually use the singleton pattern
to assure only one instance of their classes.
If containers like Spring are used for component creation, it is typically not
required any more to implement the Singleton pattern manually. The same is
true for many applications of the factory pattern. In Spring the configuration
of a component (Java bean) can be defined in the Spring-config file. On
option is to retrieve the component as Singleton. Spring then deals with the
lifecycle of the object.
Structure
Sample
public class PrintSpooler {
// Private constructor suppresses generation of a (public) default
constructor
private PrintSpooler() {}
private static class SingletonHolder {
private static PrintSpooler instance = new PrintSpooler();
}
public static PrintSpooler getInstance() {
return SingletonHolder.instance;
}
}
More generally, the term factory method is often used to refer to any method whose main
purpose is creation of objects.
Applicability / Uses
Use a Factory Method when
classes delegate responsibility to one of several helper subclasses, and you want to
localize the knowledge of which helper subclass is the delegate.
Related Patterns
Abstract Factory: is more high-level than a factory method, it is common for objects
obtained through an abstract factory to have factory methods.
Varieties
Different implementations of factory methods are available:
Factory Method is inherited, generics can help here (root class is an interface)
Structure
Sample
We have an abstract class which defines a product. This is the supertype of
all products which are produced by the factory:
public abstract class Product {
public float getPrice();
public String getProductType() {
return "Unknown Product";
}
}
}
public String getProductType() {
return "Milk";
}
}
public class Sugar extends Product {
private float price;
protected Sugar(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
public String getProductType() {
return "Sugar";
}
}
// Shopping!
cart[0] = ProductFactory.createProduct("Milk");
cart[1] = ProductFactory.createProduct("Sugar");
cart[2] = ProductFactory.createProduct("Bread");
All we need now is the factory with its factory-method. The factory method
contains all initialization data for the objects it produces:
public class ProductFactory {
pulbic static Product createProduct(String what) {
// When sugar is requested, we return sugar:
if (what.equals("Sugar")) {
return new Sugar(1.49F);
}
// When milk is needed, we return milk:
else if (what.equals("Milk")) {
return new Milk(0.99F);
}
Applicability / Uses
Use the Object Pool pattern when:
several parts of your application require the same objects at different times.
Related Patterns
Factory Method: The Factory Method pattern can be used to encapsulate the creation
logic for objects. However, it does not manage them after their creation, the object
pool pattern keeps track of the objects it creates.
Structure
This Object Pool handles storage, tracking and expiration times. The
instantiation, validation and destruction of specific object types must be
handled by subclassing.
Sample
Let us create our ObjectPool class. This code, while heavily modified to
reflect new features in the Java language, is based on an example found on
JavaWorld.com - Build your own ObjectPool in Java to boost app speed, by
Thomas E. Davis, 06/01/98
public abstract class ObjectPool<T> {
private long expirationTime;
private Hashtable<T, Long> locked, unlocked;
public ObjectPool() {
expirationTime = 30000; // 30 seconds
locked = new Hashtable<T, Long>();
unlocked = new Hashtable<T, Long>();
}
protected abstract T create();
}
this.dsn = dsn;
this.usr = usr;
this.pwd = pwd;
}
@Override
protected Connection create() {
try {
return (DriverManager.getConnection(dsn, usr, pwd));
} catch (SQLException e) {
e.printStackTrace();
return (null);
}
}
@Override
public void expire(Connection o) {
try {
((Connection) o).close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public boolean validate(Connection o) {
try {
return (!((Connection) o).isClosed());
} catch (SQLException e) {
e.printStackTrace();
return (false);
}
}
}
}
}
Iterator Pattern
A form of the visitor pattern that walks a data structure using a common interface,
retrieving the elements one by one without exposing the underlying representation. The
iterator encapsulates the internal structure of how the iteration works.
In Java, you will see alot of code like this:
List users = new LinkedList();
for (Iterator it = users.iterator(); it.hasNext();) {
User u = (User) it.next();
...
}
Applicability / Uses
For example, if your program uses 4 different kinds of data structures - a
tree, linked list, hash table and an array which all need to be processed by
methods to sort, search and next (iterate one by one) then you would need
a total of 12 different algorithms. Using an iterator this can be reduced to 7.
The Iterator Pattern is also known under the name "Cursor".
Related Patterns
The Composite pattern usually lets Iterators walk its data structure.
Structure
UML diagram of the sample code shown:
Sample
This sample code is based on the article "Behavioral Patterns - Iterator
Pattern" from allappforum.com
In Java, you will see a lot of iterators. Lets apply our example to a real world
application like channel-surfing on a Television system and lets build a
remote control implemented in Java:
public interface Iiterator {
public Channel nextChannel(int currentChannel);
public Channel prevChannel(int currentChannel);
}
Now lets say all remote controls produced must conform to this interface, its
like a specification given too all remote control manufacturing companies.
Look at the interface pattern for more on this. Lets see how the interface is
implemented, this code already resides (of course in compiled form) on the
remote control:
public class ChannelSurfer implements Iiterator {
public Channel nextChannel(int currentChannel) {
Channel channel = new Channel(currentChannel+1);
return channel;
}
While programming in Java you will use iterators allot, the facilities which
Java provides with its collection classes is extensive, so you will mostly be
using existing iterators like the one for a LinkedList:
List users = new LinkedList();
for (Iterator it = users.iterator(); it.hasNext();) {
User u = (User) it.next();
...
}
Observer
The aim of the Observer-Pattern is to define a one-to-many dependency between objects so
that when the object on the "one-side" changes state, all its dependents are notified and
updated automatically.
The Observer/Observable-Pattern is known under many different Names, each flavor is used
for a special purpose and has a slightly different form.
Most common other names for this pattern are
Producer/Consumer
Publish/Subscribe
Dependents
The main idea of the Observer-Pattern is that an object (the observer) that always requires
actual data of another object (the observable or subject).
The fist solution that comes into mind might be to continuously ask the subject for changes
of the data desired and if necessary load the data. The mechanism of continuously asking
the subject for changes, also called polling has the main disadvantage of causing an
unnecessary high system load.
A much better idea would be to delegate the responsibility for informing objects about new
data to the producer or manager of the data. Through the producer - in our case the subject
- knows exactly when the data has changed and therefore other objects should be informed.
This is the Observer pattern.
There are basically two ways of notifying the observers: One is the push model while the
other is the pull model. The main difference is, that using the pull model the observer has
to pull the data needed by itself, while when using the push model the observable sends
the data along with the notification.
Applicability / Uses
The Observer-Pattern is especially useful when
a change in one object requires changing others, and you don't know how many
objects need to change their state, or when
an object should be able to notify other objects without making assumptions about
what those objects are.
Related Patterns
Structure
Sample
The Story for this example is the following: We have a Number-Bag which
contains numbers (integers) and someone can add a number at any time.
But there are several objects which have to know the content of the bag.
In this example, the Number-Bag is the Observable:
public class Observable {
private List<Observer> observers; // The list of observers to be notified
// on new items in the "Bag"
private List<Integer> content;
// The "Bag"
// Initialized in Constructor
public void addNumber(int nr) {
content.add(nr);
notifyObservers();
}
public List<Integer> getContent() {
return content;
}
Event Listener
Events are messages that are sent from one object to another. The component sending the
event (aka firing the event) is the producer, the component receiving the event (aka
handling the event) is the consumer. The producer of an event should have the ability to
add and delete listeners for the events produced by itself.
In short, a predefined method of the listener is invoked by the producer when an event is
fired.
Applicability / Uses
The Event Listener pattern is commonly used in the Java-Libraries, especially
within AWT (java.awt.*) and SWING (javax.swing.*). Handling UserInteractions, such as clicking on a button, is realized through Events and
Event-Listeners
Related Patterns
Observer: The Event Listener pattern is a special flavor of the Observer pattern
Structure
UML diagram of the sample code:
Sample
In this example we will create a new JFrame, containing a single Button.
When the user presses the button, the window-title will change.
public class TestGUIEvents extends JFrame {
int clickCount;
public TestGUIEvents() {
clickCount = 0;
setTitle("Click-Count: " + clickCount);
JButton button = new JButton("Click me!");
button.addActionListener(new ButtonListener());
add(button);
pack();
}
public static void main(String[] args) {
new TestGUIEvents().setVisible(true);
}
Strategy Pattern
The strategy pattern embodies two core principles of object-oriented programming, it
encapsulates the concept that varies and lets programmers code to an interface, not an
implementation.
Canonical view of the strategy pattern:
The strategy pattern shows you how to implement different behaviors (algorithms) in a
seperate class hierarchy with an interface at its root. The goal is to decouple the objects
which use your encapsulated "strategies" (the context) and the strategies (algorithms)
themselves so that they can vary independently.
The strategy pattern is also known under the name "Policy".
Applicability / Uses
Use the strategy pattern when:
many related classes (tightly coupled classes) differ in their behavior. Strategy lets
you "configure" a class with one of many behaviors.
you need different variants of an algorithm. For example, java swing uses the
strategy pattern to implement different styles of borders on JComponents. Since
these strategy variants can also be implemented in a class hierarchy they become
interchangeable.
you want to decouple complex, algorithm specific data structures from the clients
which use them. With the strategy pattern you can encapsulate complex data
structures and avoid exposing them to the rest of your program.
Related Patterns
Structure
UML diagram of the sample code:
Sample
To show you a real world example of the strategy pattern in action we will
have a look at how Java Swing uses the strategy pattern to draw borders
around its components. Borders for Swing components are drawn by the
JComponent class with a method called paintBorder(g: Graphics).
JComponent is the base class for all Swing components. Lets take a closer
look at this method now:
protected void paintBorder(Graphics g) {
Border border = getBorder();
if (border != null) {
border.paintBorder(this, g, 0, 0, getWidth(), getHeight());
}
}
4. In your Context class, implement public setter and getter methods for the Strategy
object.