Created
February 4, 2024 20:24
-
-
Save isidroamv/a9b81f56fcef593d80b8ec2978ee4880 to your computer and use it in GitHub Desktop.
HeaFirstDesignPatters: Strategy - Composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface FlyBehavior { | |
fly(): void; | |
} | |
interface QuackBehavior { | |
quack(): void; | |
} | |
class FlyWithWings implements FlyBehavior { | |
fly(): void { | |
console.log("I'm flying!!"); | |
} | |
} | |
class FlyNoWay implements FlyBehavior { | |
fly(): void { | |
console.log("I can't fly :("); | |
} | |
} | |
class FlyRocketPowered implements FlyBehavior { | |
fly(): void { | |
console.log("I'm flying with a rocket!"); | |
} | |
} | |
interface QuackBehavior { | |
quack(): void; | |
} | |
class Quack implements QuackBehavior { | |
quack(): void { | |
console.log("Quack"); | |
} | |
} | |
class MuteQuack implements QuackBehavior { | |
quack(): void { | |
console.log("<< Silence >>"); | |
} | |
} | |
class Squeak implements QuackBehavior { | |
quack(): void { | |
console.log("Squeak"); | |
} | |
} | |
abstract class Duck { | |
private _flyBehavior: FlyBehavior; | |
private _quackBehavior: QuackBehavior; | |
abstract swim(): void; | |
abstract display(): void; | |
abstract performFly(): void; | |
abstract performQuack(): void; | |
set flyBehavior(fb: FlyBehavior) { | |
this._flyBehavior = fb; | |
} | |
get flyBehavior(): FlyBehavior { | |
return this._flyBehavior; | |
} | |
set quackBehavior(qb: QuackBehavior) { | |
this._quackBehavior = qb; | |
} | |
get quackBehavior(): QuackBehavior { | |
return this._quackBehavior; | |
} | |
} | |
class RuberDuck extends Duck { | |
constructor() { | |
super(); | |
this.flyBehavior = new FlyWithWings(); | |
this.quackBehavior = new Squeak(); | |
} | |
swim(): void { | |
console.log("Swimming"); | |
} | |
display(): void { | |
console.log("I'm a rubber duck!"); | |
} | |
performFly(): void { | |
this.flyBehavior.fly(); | |
} | |
performQuack(): void { | |
this.quackBehavior.quack(); | |
} | |
} | |
//////////////////////////////// | |
//// IMPLEMENTATION EXAMPLE //// | |
/////////////////////////////// | |
const d = new RuberDuck(); | |
// Use Composition Pattern implemented in the Duck class to perform behavior | |
d.performFly(); | |
d.performQuack(); | |
// Use Strategy Pattern to change behavior | |
d.flyBehavior = new FlyNoWay(); | |
d.performFly(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment