Design Patterns Applications Programming What is design patterns? - - PDF document

design patterns
SMART_READER_LITE
LIVE PREVIEW

Design Patterns Applications Programming What is design patterns? - - PDF document

10/26/2011 G52APR Design Patterns Applications Programming What is design patterns? The design patterns are language- Design Patterns 1 independent strategies for solving common object-oriented design problems. Jiawei Li (Michael)


slide-1
SLIDE 1

10/26/2011 1

Design Patterns 1

Jiawei Li (Michael) email: jwl@cs.nott.ac.uk

http://www.cs.nott.ac.uk/~jwl/G52APR

G52APR Applications Programming

Design Patterns

  • What is design patterns?

– The design patterns are language- independent strategies for solving common

  • bject-oriented design problems.

2

Design Patterns

  • How many design patterns?

– Many.

  • Why use design patterns?

– Solutions to complex problems – Code reuse – To be a good Java developer

3

Outline

  • Commonly recurring patterns of OO

design

  • A simple example
  • Adapter pattern
  • Composite pattern
  • Solving complex problems

4

Commonly recurring patterns of OO design

  • Creational Patterns
  • Structural patterns
  • Behavioural patterns
  • J2EE patterns

5

  • Adaptor
  • Composite
  • Strategy
  • Decorator
  • Observer
  • Factory method
  • Iterator

Bicycles Simulator

  • Various bicycles

– Mountain bicycles – Road bicycles – Child bicycles …

  • Various actions

– Speed up – Changing gear …

6

slide-2
SLIDE 2

10/26/2011 2

Bicycle’s Inheritance

  • Many different bicycles
  • Classic case for inheritance
  • Base-class of Bicycle, from which

specialized Bicycle classes inherit

7

Bicycle class

8

Bicycle Road Bicycle Mountain Bicycle Child Bicycle

Bicycle class

  • UML Representation for a Class
  • UML stands for Unified Modeling Language

9

Class Name

Attribute Attribute Operation Operation

10

UML Notation

Inheritance Aggregation Composition

Bicycle class Inheritance

11

Bicycle Road Bicycle Mountain Bicycle Child Bicycle Superclass Subclasses

  • Abstract classes: cannot be instantiated.
  • Abstract methods: without an implementation.

Bicycle class Inheritance

// source file name bicycle.java public abstract class bicycle{ private int gear; private boolean front_brake; private boolean rear_brake; public void setGear(int newValue); public void getMaximumSpeed(); … } public class road_bicycle extends bicycle{ … } public class mountain_bicycle extends bicycle{ … }

12

slide-3
SLIDE 3

10/26/2011 3

Inheritance summary

  • A class inherits fields and methods from all its

superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.

  • An abstract class can only be subclassed; it

cannot be instantiated. An abstract class can contain abstract methods.

  • You can prevent a class from being subclassed by

using the final keyword in the class's declaration. Similarly, you can prevent a method from being

  • verridden by declaring it as a final method.

13

Bicycles Simulator v2

  • More features of bicycles

– Foldable – With motor

14

Bicycles Simulator v2

public abstract class bicycle{ … public void setGear(int newValue); public void setFold(boolean newState ); public void setMotor(double newSpeed); … }

15

Bicycles Simulator v2

  • Some features are not appropriate for all

subclasses of Bicycle.

  • If those features are implemented in the

methods of superclass, subclasses inherit inappropriate behaviour.

  • Need to override the methods.
  • Is Inheritance the right model here?

16

Bicycle Inheritance

  • Disabling operations on derived classes
  • Maintenance problem

– Every new bicycle subclass will require you to consider overriding setFold()/setMotor() – Danger of not overriding methods on new bicycles…

17

Interface

  • Does the behaviour belong in the

baseclass in the first place?

  • Put it in an interface
  • Interfaces are a collection of abstract

methods that an Object implements

  • Object can support multiple interfaces (no

multiple inheritance!)

18

slide-4
SLIDE 4

10/26/2011 4

Object Interface

  • Client can ask an object if it supports an

interface.

  • If it does it can use the interface, if not try

something else.

  • Interfaces are declarations, they contain

no code to implement methods.

19

Usage of interfaces

interface foldable { void setFold(boolean newState); } interface with_motor { void setMotor(double newSpeed); } class myBike1 extends bicycle implements foldable { public void setFold(boolean newState){ …} … } class myBike2 extends bicycle implements foldable, with_motor { … }

20

Bicycle class hierarchy

21

Duplicate Code

  • Interfaces have no code
  • Each bicycle subclass must have its own

implementation for each interface.

  • Any change to an implementation must be

made to every sub-class that supports it

22

Adapter

  • The intent of Adapter is to provide the

interface that a client expects while using a existing class.

  • A new subclass of Bicycle: Bicycle_without_pedals

interface no_pedal { void setNoPedal(); } class myBike1 extends bicycle implements no_pedal { … }

23

Adapter

  • When a developer of client code thoughtfully defines the client‘s

needs, you may be able to fulfill the interface by adapting existing code.

24

ExistingClass UsefulMethod() NewClass RequiredMethod() <<interface>> RequiredMethod()

slide-5
SLIDE 5

10/26/2011 5

Object Adapter

  • ExistingClass is instantiated in NewClass so that UsefulMethod can

be used. It can be dangerous if you don‘t override all the methods that might be called.

25

ExistingClass UsefulMethod() NewClass RequiredMethod() RequiredClass RequiredMethod()

26

Object Adapter example Adapter summary

  • The Adapter pattern lets you use an

existing class to meet new requirements.

  • Class adapter: create new class that

implements new interface and subclasses an existing class.

  • Object adapter: create a new client

subclass that uses an instance of the existing class.

27

Change

  • Change is the one constant in software

development

  • Don‘t make rigid designs
  • Changing something should be easy and

require the least amount of effort

28

Design Principle

“Identify the aspects of your application that vary and separate them from what stays the same”

29

Design Principle

  • Some parts of the application are varying

with new requirements, others don‘t

  • Encapsulate the bits that change into a

new object so that it can be changed easily

  • This is at the heart of every design pattern

30

slide-6
SLIDE 6

10/26/2011 6

Changing Bicycles

  • Thought we had a good design for our

bicycle simulator

  • But changing features may require major

changes

  • How do we make it a good design?

31

Bicycle (re)design

  • Bicycle class seems to work

– Apart from methods e.g. setFold()

  • Separate these methods off into new

classes or interfaces

– Foldable behaviour – With Moter behaviour – Without Pedal behaviour – ...

32

Bicycle Behaviour

  • Keep things flexible
  • Instances of Bicycle are assigned

behaviours

  • Can we change a behaviour dynamically?

– To make a foldable bicycle non-foldable?

  • Mutators to change Bicycle‘s behaviour at

runtime

33

Mutators: setter() methods

Design Principle

―Program to an interface, not an implementation‖

34 35

Program to an interface

Interface A{ method()… }; Class B implement A { method()...}; // program 1: Class X { private A a1; public void useA (A b1){ a1 = b1; a1.method(); } // program 2: Class X { private B b1; public void useB(){ b1.method(); }

Behaviour Interfaces

  • FoldableBehaviour and

WithMotorBehaviour

  • Gives us flexibility

– Don‘t inherit any implementation – Bicycle‘s aren‘t tied to an implementation

36

slide-7
SLIDE 7

10/26/2011 7

37

<<interface>> foldable setFold() FoldableBicycle setFold() { /* Fold the bike */ } Non-foldableBicycle setFold() { /* Do nothing */ }

Integrating Behaviours

  • Interface type — don‘t want to bind this to

an implementation

  • Add instance variables for the behaviours

– FoldableBehaviour – WithMotorBehaviour – …

  • Add methods to call the behaviour

38

public abstract class Bicycle { protected FoldableBehaviour fordable; protected WithMotorBehaviour with_motor; … } public class myBike extends Bicycle { public FoldableBehaviour getFordable { return this.fordable;} public void setFordable(FoldableBehaviour state) { fordable = state.setFold(); }; … }

39

What is happening?

  • When myBike is created:

– Creates objects for correct behaviours – Sets variables to instantiate existing classes (interfaces)

  • When setFoldable() called, setFold() is

called on the newly created object

  • Equivalent for setMotor()…

40

Strategy Pattern

  • Example of the ‗Strategy‘ Pattern
  • Strategy Pattern defines a family of

algorithms, encapsulates each one, and makes them interchangeable.

  • Strategy lets the algorithm vary

independently from clients that use it

41 42

Exercise

interface Monster { void menace();} interface DangerousMonster extends Monster { void destroy();} interface Lethal { void kill();} class Zombie implements DangerousMonster { public void menace() {// some code here } public void destroy() {// some code here } } interface Vampire extends DangerousMonster, Lethal { void drinkBlood();} class VeryBadVampire implements Vampire { public void menace() {// some code here } public void destroy() {// some code here } public void kill() {// some code here } public void drinkBlood() {// some code here } }

** You need create three new classes: Monster1: is a zombie and has kill() method Monster2: has the methods of kill(), destroy(), and a new method fly() Monster3: is a VeryBadVampire but does not have kill() method

slide-8
SLIDE 8

10/26/2011 8

Reading

  • ErichGamma, RichardHelm, RalphJohnson, and

JohnVlissides (the Gang Of Four), Design Patterns: Elements of Reusable Object-Oriented Software, Addison Wesley Professional, 1994

  • Steven J. Metsker and William C. Wake, Design

Patterns in Java, Addison Wesley, 2006

  • http://www.javacamp.org/designPattern/

43