Design Patterns usage in Java API.

Definition

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design…
This is the wikipedia description of Design Pattern in software engineering. To se more go here. There are also listed most important design patterns, divided into groups.

In this post we cover following design patterns: Template Method, Observer, Composite, Decorator.


Important

In my opinion the important thing is to fully understand the design pattern. There are few things, when combine, will give you full understanding of a pattern:

  • Be able to explain pattern to somebody else (this can be useful or even crucial on interview to new company).
  • Be able to spot, and name design pattern in code.
  • Be able to implement one.
  • Know in which situations design patterns is required and where not.


Usage

I figured out that it will be very easy for any Java developer to remember construction of design pattern if he/she knew the usage in Java API.
Below I have several examples of usage design pattern in Java API.


Templete Method

Description on wiki is here
In Java API Template Method is implemented in Thread. When you create custom thread by extending the Thread class, you need to implement run() method like the one below. In which you write code responsible for execution. But after creating instance of the thread you run it by invoking start() method.

		Thread thread = new Thread() {
			@Override
			public void run() {
				// code which you want to execute.
			}
		};
		thread.start();

When you go to java source, you can read javadoc from start() method.

    /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {


Observer

Description on wiki is here
This is used in many places for example in Swing/AWT library to handle Button clicks, also for the same behavior in android. Here is java example.
To handle situation after clicking on button in Swing, you need to register ActionListener in Button object.

		ActionListener actionListener = new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("Button clicked");
			}
		};
		JButton button = new JButton("Click me");
		button.addActionListener(actionListener);


Composite

Description on wiki is here
This pattern is also used in Swing. When you have many objects in one JPanel, and you may have another JPanel objects in the root one. This creates a hierarchy of UI Components.
To be displayed, each component implements paint() method. This method paints itself and all its children.

    ...
     * This method actually delegates the work of painting to three
     * protected methods: <code>paintComponent</code>,
     * <code>paintBorder</code>,
     * and <code>paintChildren</code>.  They're called in the order
    ...
    public void paint(Graphics g) {
    ... 
                if (!printing) {
                    paintChildren(co);
                }
                else {
                    printChildren(co);
                }
    ...
    }

printChildren() method is quite complicated, but basically it iterates over all its children and invokes paint() on them.


Decorator

Description on wiki is here
Pattern is used in java.io package.

BufferedReader bufferedReader 
    = new BufferedReader(
        new InputStreamReader(
            new FileInputStream(
                new File("file_name.txt"))));

In this example you have sequence of creating new objects to handle reading from file. You create File object which you decorate with FileInputStream and so on.
Each object provide better functionality for developer.
File provides functionality related to file:

...
    public String getName() {
...
    public String getParent() {
...
    public boolean canRead() {
...
    public boolean canWrite() {
...

FileInputStream provides functionality for low level reading:

...
    private native void open(String name)
...
    public native int read() throws IOException;
...
    public int read(byte b[]) throws IOException {
...
    public void close() throws IOException {
...

From low level reading bytes in file, you are getting higher level functionality to read whole line in BufferedReader.


Reklamy

Jedna uwaga do wpisu “Design Patterns usage in Java API.

Skomentuj

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj / Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj / Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj / Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj / Zmień )

Connecting to %s