220 likes | 454 Views
Sim-U-Duck. Welcome to Design Patterns. Simple Sim-U-Duck design. By Joe the programmer. A new requirement. Ducks must be able to fly!. A new requirement. Ducks must be able to fly!. Something went wrong. What happened?.
E N D
Sim-U-Duck Welcome to Design Patterns
Simple Sim-U-Duck design • By Joe the programmer
A new requirement • Ducks must be able to fly!
A new requirement • Ducks must be able to fly!
Something went wrong... What happened? A localized update to the code caused a non-local side effect (flying rubber ducks)!
Alternatives • Override methods in subclasses RubberDuck : Duck DecoyDuck : Duck Display() {//rubber duck} Quack(){//squeak} Fly(){//do nothing} Display() {//decoy duck} Fly(){//do nothing} MallardDuck : Duck Duck RedheadDuck : Duck Display() {//mallard duck} Display() //abstract Quack(){//quack} Fly(){//fly} Display() {//redhead duck}
Alternatives • Create interfaces Flyable and Quackable
Alternatives • Create interfaces Flyable and Quackable
New requirement: 48 duck classes! I want a solution withoutduplicate code
Designing the Duck behaviors <<interface>> FlyBehavior FlyWithWings FlyNoWay Fly() { //implements duck flying } Fly() { //do nothing – can’t fly } Fly()
Implementing the Duck behaviors <<interface>> FlyBehavior FlyWithWings <<interface>> QuackBehavior FlyNoWay MuteQuack Squeak Quack Fly() { //implements duck flying } Fly() { //do nothing – can’t fly } Quack() { //do nothing – can’t quack } Quack() { //rubber duckie squeak } Quack() { //implements duck quacking } Fly() Quack()
Design Principle N°3 • HAS-A can be better than IS-A