Recent Changes - Search:

Software Engineering

This website demonstrates using wikis as teaching and learning tool.

The course instructor is also happy to share the teaching materials here with those who find it readable.

Object Design and Design Patterns

A Software Engineering Lecture by Steven Choy

Lecture Overview: In this lecture, we start to learn object design and design patterns.

Object design is about identifying additional solution-domain objects and refining existing objects. Object design includes the following activities:

  • Reuse : use inheritance and composition/delegation, identify off-the-shelf framework, and apply design patterns
  • Service specification : describe interface of classes precisely
  • Restructuring : transform the object model to increase code reuse or meet other design goals such as readability and maintainability
  • Optimization address performance goals such as response time and throughput

Design patterns take the reuse concept a step further. A design pattern encapsulates a specific way that a number of different objects work together. Different design patterns can be applied in certain situations to achieve specific benefits.

Reading: Chapter 8 of the textbook Object Design: Reusing Pattern Solutions


Where are we now?

Object Design Overview

Deliverables of System Analysis

Software Design Document

1. Introduction

1.1 Purpose of the system
1.2 Design Goals
1.3 Definition, acronyms and abbreviations
1.4 References
1.5 Overview

2. Software Architecture

2.1 Overview
2.2 Subsystem Decomposition
2.3 Hardware/software mapping
2.4 Persistent data management
2.5 Access control and security
2.6 Global Software Control
2.7 Exception Handling Stragtegies
2.8 Boundary Conditions

3. Subsystem
4. Glossary

Application Domain Object vs Solution Domain Object

  • Application Domain Objects
    • Represent concepts of the domain that are relevant to the system.
    • They are identified by the application domain specialists and by the end users.
  • Solution Domain Objects
    • Represent concepts that do not have a counterpart in the application domain
    • They are identified by the developers

Example

Object Design Activities

  • Reuse (Covered in this lecture)
    • Use of Inheritance and Composition/Delegation
    • Identify Off-the-shelf framework
    • Design Patterns
  • Interface Specification (Covered later)
    • Describe interface of classes precisely
  • Restructuring (Covered later)
    • Transform the object model to increase code reuse or meet other design goals such as readability and maintainability
  • Optimization (Covered later)
    • Address performance goals such as response time and throughput

Main topics in this lecture

  • Reuse Concepts
  • Use of Inheritance
  • Inheritance vs Composition
  • Design Patterns (next lecture)
    • Creational Pattern
    • Structural Pattern
    • Behavioral Pattern

Reuse Concepts

Why Reuse?

  • Business requirements are always changing. The system you design for today may not be the same for tomorrow.
  • You can't say "No, my system is not designed for that business requirement."
  • You don't want to rewrite your system when there are some new requirements raise up.
  • ⇒ The need for reusable and flexible design.

Reuse of Classes

  • Two fundamental ways of reuse:
    • The use of inheritance
    • The use of composition

Inheritance Overview

  • Inheritance is one of merits of OO Design
  • Extend from a Base Class
    • Add in new operations
    • Overwrite the existing operations
    • Reuse operations in the base class
  • Promote code reuse, reduce redundancy and make your class extensible

Composition Overview

  • An alternative to inheritance for code reuse
  • Implementation view: Class A holds an instance of Class B . Class A can call on methods of Class B.

Example

Inheritance: Manager class inherites from Employee class
Composition: Manager class holds a reference to Employee class using instance variable

Inheritance Problem

  • The Ripple Effect: A change in Base Class may lead to change of other subclasses
  • Example: Modify an interface in base class may result compilation failure of the subclasses

Inheritance Problem Example

  • What if the return value of getSalary() method is change?

The Composition Alternative

  • For the inheritance problem, what if composition is used for code reuse?

Inheritance or Composition?

  • When using inheritance, make sure the base class and subclass has a is-a relationship.
  • Generally, favor composition over inheritance for code reuse.
  • Composition helps you keep each class encapsulated.

Design Pattern

A little bit History

  • Pattern is not firstly adopted by software experts
  • In 1970s, Christopher Alexander wrote a number of books about patterns in architecture and civil engineering
"Each pattern is a three-part rule, which expresses a relation between a certain context, a problem and a solution."
Christopher Alexander
"Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice. "
Christopher Alexander
  • Software engineers inspired by the pattern principle and applied it in software design
  • Pattern in software were popularized by the book "Design Patterns: Elements of Reusable Object-Oriented Software", written by Gang of Four or GoF

What's Design Pattern?

  • Design patterns are recurring solutions to design problems you see over and over again [Alpert, et al.,1998]
  • Design patterns constitute a set of rules describing how to accomplish certain tasks in the realm of software development [Pree, 1994]
  • Design patterns are template solutions that developrs have refined over time to solve a range of recurring problems [Gamma et al., 1994]

Pattern Characteristics

  • Patterns are not created but observed through experience
  • Patterns avoid you to re-invent the wheel
  • Patterns are reusable artifacts
  • Patterns undergo continuous improvement
  • Patterns can be used together to solve larger problem

Benefits of Using Patterns

  • Reuse proven solutions
    • You do not need to reinvent your wheel
    • The best solution is already there
  • Establish common vocabulary
    • Pattern provides developers a common point of reference to communicate design
  • Have a higher perspective on analysis and design
    • Free you from dealing with details too early
  • Improve flexibility of your code

"Gang of Four" Design Patterns

  • The GoF revealed a total of 23 design patterns and categorized them
  • Creational Patterns
    • Patterns that are for object creations
    • But rather than just instantiate objects directly, they defines the best ways to create objects
  • Structural Patterns
    • Patterns that helps you compose objects into larger structures
  • Behavioral Patterns
    • Patterns that concerns with interactions between objects
    • Help developers define the communication between objects in the system

Pattern Categories

Creational Pattern
Abstract Factory Creates an instance of several families of classe
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Pattern
Adapter Match interfaces of different classes
Bridge Separates an object's interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Facade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Pattern
Chain of Responsibility A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Captures and restores an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behaviour when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defers the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change

Documenting Design Pattern

  • A design pattern has four elements:
    • A name
      • Name of the pattern
    • A problem description
      • Describe the problem/situation faced by developers in which the pattern can be used
    • A solution
      • Describe the solution approach and the solution elements in detail
    • A set of consequences
      • Describe the trade-offs of pattern, that the pros and cons of using the pattern

Strategies Behind Design Patterns

  • The GoF suggests the following strategies for creating good OO Design:
    • Design to interface
    • Favour composition over inheritance
    • Find what varies and encapsulate it

Design Pattern: Singleton

How do you ensure only a single instance of class is instantiated?

Singleton Pattern

  • What did GoF say?
    • Ensure a single instance of a class
    • Provide a global access point to the instance
  • How does it work?

Singleton Implementation

class Singleton {

	private static Singleton instance = null;
 	private Singleton () {
  	}

	public static Singleton getInstance() {
		if (instance == null) { 
		     instance = new Singleton ();
		}
		return instance;
	}

	// Other method implementations

}

Singleton Example

Design Pattern: Observer

What if a group of objects needs to update themselves when some object changes state?

The Observer Pattern

  • This pattern solves a common problem:
    • What if a group of objects needs to update themselves when some object changes state?
  • aka Dependents & Publish-Subscribe
    • An object notifies other objects if it changes

Implement in Java

  • There are two types of objects used to implement the observer pattern in Java
    • Interface Observer
    • Class Observable
  • The Observable object keeps track of everybody who wants to be informed when a change happens.
  • When someone says "OK, everybody should check and potentially update yourselves,"
    • The Observable object performs the notifyObservers( ) method for each one on the list.
    • The notifyObservers( ) method is part of the base class Observable.
  • An Observer object is some object that implements the Observer interface
  • The Observer object will register with an Observable object.
  • When a change has been made in the Observable object, the Observable object will call the Observer object's update( ) method.

Java API Reference

Example

public class Person extends Observable {

	private String forename ;
	private String surname ;
	private int age ;

	... ...

	public void setForename(String f) {
	    	forename = f ;
            	setChanged();
            	notifyObservers();
	} 

	public void setSurname(String s) {
		... ...
	} 

	public void setAge(int a) {
		... ...
	} 

}

public class PersonView extends JFrame

	implements ActionListener, Observer {

	... ...

	public void update( Observable o, Object arg ) {
		Person aperson = ( Person ) o;
		... ...
		al.setText( "Age: " + String.valueOf( aperson.getAge() ) );
	}

}

public class ControllerTest {

	public static void main( String[] args ) {

		Person p = new Person( "Ivor", "Pattern", 23 );
		PersonView pfr = new PersonView( "Person GUI" );
		p.addObserver( pfr );

		pfr.setLocation( 200, 200 );
		pfr.setVisible( true );
		try {
			for( int i = 0; i <= 300; i++ ) {
				p.increaseAge( 1 );
				Thread.sleep( 1000 );
			}
		}
		catch( Exception e ) {
			System.out.println( e );
		}
	}

}


Extra materials for your to probe further

  • The Open-Closed principle is an important principle for a good object-oriented design (OOD).
It states that well-designed code should be open for extension and closed for modification. In other words, in a well-designed program, new functionalities are added by adding new code rather than by modifying already working code. It is the foundation for building software that is maintainable and reusable. This principle was coined by Bertrand Meyer in his book titled Object Oriented Software Construction. The second edition of this book is introduced here in Eiffel Software.
An article obtained from Object Mentor give a very good introduction on the Open-Closed principle. Here is the direct link to this article: The Open-Closed Principle (PDF file, 69 KB).

Thanks for Reading

If you would rather like to have this lecture note in printed format, please click the print action link in the top right corner.

If you find any problem in this lecture note, please feel free to tell Steven by steven@findaway.hk

Edit - History - Print - Recent Changes - Search
Page last modified on September 09, 2009, at 11:00 PM