CS 210 Final Review November 28, 2006. CS 210 Adapter Pattern

Preview:

Citation preview

CS 210

Final Review

November 28, 2006

CS 210

Adapter Pattern

Adapters in real life

Page 236 – Head First Design Patterns

Object-Oriented Adapters

Page 237 Head First Design Patterns

Turkey that wants to be a duck example

public interface Duck {

public void quack();

public void fly();

}

Subclass of a duck – Mallard Duck

public class MallardDuck implements Duck {

public void quack() {

System.out.println("Quack");

}

public void fly() {

System.out.println("I'm flying");

}

}

Turkey Interface

public interface Turkey {

public void gobble();

public void fly();

}

An instance of a turkey

public class WildTurkey implements Turkey {

public void gobble() {

System.out.println("Gobble gobble");

}

public void fly() {

System.out.println("I'm flying a short distance");

}

}

Turkey adapter – that makes a turkey look like a duckpublic class TurkeyAdapter implements Duck {

Turkey turkey; public TurkeyAdapter(Turkey turkey) {

this.turkey = turkey;}

public void quack() {turkey.gobble();

} public void fly() {

for(int i=0; i < 5; i++) {turkey.fly();

}}

}

Duck test drivepublic class DuckTestDrive {

public static void main(String[] args) {MallardDuck duck = new MallardDuck();

WildTurkey turkey = new WildTurkey();Duck turkeyAdapter = new TurkeyAdapter(turkey);

System.out.println("The Turkey says...");turkey.gobble();turkey.fly();

System.out.println("\nThe Duck says...");testDuck(duck);

System.out.println("\nThe TurkeyAdapter says...");testDuck(turkeyAdapter);

} static void testDuck(Duck duck) {

duck.quack();duck.fly();

}}

Test run – turkey that behaves like a duckThe Turkey says...Gobble gobbleI'm flying a short distance

The Duck says...QuackI'm flying

The TurkeyAdapter says...Gobble gobbleI'm flying a short distanceI'm flying a short distanceI'm flying a short distanceI'm flying a short distanceI'm flying a short distance

Adapter Pattern explained

Page 241 – Head First Design Patterns

Adapter Pattern defined

The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

Adapter Pattern

Page 243 – Head First Design Patterns

Façade Pattern

Simplifying complex subsystems

Page 255 – Head First Design Patterns

Watching the movie the hard way….

Page 256 – Head First Design Patterns

What needs to be done to watch a movie….

Façade Pattern defined

The Façade Pattern provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher level interface that makes the subsystem easier to use.

Façade pattern – Class Diagram

Design Principle

Principle of Least Knowledge

talk only to your immediate friends

Basically this says minimize your dependencies

Client

The client only hasone friend – andthat is a good thing

If the subsystemgets too complicatedOne can recursivelyapply the same principle.

A little comparison

Pattern Intent

DecoratorConverts one interfaceto another

AdapterDoesn’t alter the interface,But adds responsibility

Facade Makes an interface simpler

CS 210

Template Method Pattern

Abstracted Recipe method

Abstract base classpublic abstract class CaffeineBeverage { final void prepareRecipe() {

boilWater();brew();pourInCup();addCondiments();

} abstract void brew(); abstract void addCondiments(); void boilWater() {

System.out.println("Boiling water");}

void pourInCup() {System.out.println("Pouring into cup");

}}

Coffee and Tea in terms of the abstract caffeine classpublic class Coffee extends CaffeineBeverage {

public void brew() {System.out.println("Dripping Coffee through filter");

}public void addCondiments() {System.out.println("Adding Sugar and Milk");}

}

public class Tea extends CaffeineBeverage {public void brew() {

System.out.println("Steeping the tea");}public void addCondiments() {

System.out.println("Adding Lemon");}

}

Template Method Pattern defined

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Design Principle

The Hollywood Principle

Don’t call us, we’ll call you.

CS 210

Iterator Pattern

Example to motivate discussion

We have two lists (of menu items) one implemented using ArrayList and another using Arrays.

How does one work with these two implementations of lists in a uniform way?

Example here uses restaurant items

Now if we want to…

printMenu()• Print every item on the menu

printBreakfastMenu()• Print just breakfast items

printLunchMenu()• Print just lunch items

printVegetarianMenu() isItemVegetarian(name)

Iterating through breakfast items

Iterating through lunch items

Encapsulating iteration

Instead of using multiple ways to iterate through the lists, define ONE interface to iterate through the lists …

Using iterator to get breakfast items

Using iterator to get lunch items

Meet the iterator pattern…

DinerMenuIterator

Iterator Pattern defined

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Design principle applied to Iterator pattern

Iterator pattern places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation, and places the responsibility where it should be.

Iterators and collections

CS 210

Iterator & Composite Pattern

Adding to the menu scenario…

Composite Pattern defined

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Using composite pattern

Composite Pattern

Complex hierarchy of menu items

Composition treated as one entity or as parts

Operations applied to whole or parts

CS 210

State Pattern

Example: Managing States

Design using State

State Pattern defined

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

State Pattern Class Diagram

Comparison of patterns

CS 210

Proxy Pattern

Revisit the Gumball machine example

The same example covered in the State pattern

Now we want to add some monitor a collection of Gumball machines

Gumball Class

Gumball Monitor

Role of the remote Proxy

RMI Detour in looking at Proxy Pattern

Remote Methods 101

How the method call happensClient calls method

Client Helper forwards to service helper

Service helper calls the real object

Real object returns result

Service helper forwards result to client helper

Client helper returns result to client

Hooking up client and server objects

Back to Gumball machine problem

Proxy Pattern defined

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

The proxy pattern is used to create a representative object that controls access to another object, which may be remote, expensive to create or in need of securing.

Proxy Class Diagram

Summary so far.. OO Basics

• Abstraction• Encapsulation• Inheritance• Polymorphism

OO Principles• Encapsulate what varies• Favor composition over inheritance• Program to interfaces not to implementations• Strive for loosely coupled designs between objects that interact• Classes should be open for extension but closed for modification.• Depend on abstracts. Do not depend on concrete classes.• Only talk to your friends• Don’t call us, we will call you• A class should have only one reason to change.

Summary so far… OO Patterns

• 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.

• Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

• Decorator Pattern – attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative for sub-classing for extending functionality

• Abstractor Factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

• Factory Method – Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to the subclasses.

• Command Pattern – Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

OO Patterns - Continued• The Adapter Pattern converts the interface of a class into another

interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

• The Façade Pattern provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher level interface that makes the subsystem easier to use.

• Template Method defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

• Iterator - provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

• The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

• The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

• The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

Recommended