策略模式

Posted on Sep 1, 2022
abstract class Duck {
    quack(){
        console.log('呱呱叫')
    }
    swim(){
        console.log('游泳')
    }
    abstract display() // 各种鸭子的外观不同,此为抽象方法
}

class GreenDuck extends Duck {
    display() {
        console.log('绿色的头')
    }
}

class RedDuck extends Duck {
    display() {
        console.log('红色的头')
    }
}

// 还有很多其他类型的鸭子继承了Duck
class OtherDuck extends Duck {
    display() {
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
abstract class Duck {
    quack(){
        console.log('呱呱叫')
    }
    swim(){
        console.log('游泳')
    }
    abstract display() // 各种鸭子的外观不同,此为抽象方法
    fly(){
        console.log('飞')
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class RubberDuck {
    quack(){
        // 覆盖成吱吱叫
    }

    display(){
        // 外观是橡皮鸭
    }
    fly(){
        console.log('飞')
    }
}
interface Flyable{
    fly()
}
interface Quackable {
    quack()
}
class Duck{
    swim(){}
    display(){}
}
class MallardDuck extends Duck implements Flyable, Quackable {
    display(){}
    fly(){}
    quack(){}
}
class RedheadDuck extends Duck implements Flyable, Quackable {
    display(){}
    fly(){}
    quack(){}
}
class RubberDuck extends Duck implements Quackable {
    display(){}
    quack(){}
}
class DecoyDuck extends Duck {
    display(){}
}
interface QuackBehavior {
    quack()
}

interface FlyBehavior {
    fly()
}

class FlyWithWings implements FlyBehavior {
    fly() {
        //    实现鸭子的飞行动作
    }
}

class FlyNoWay implements FlyBehavior {
    fly() {
        // 什么都不做,不会飞
    }
}

class Duck {
    protected flyBehavior: FlyBehavior
    protected quackBehavior: QuackBehavior

    swim() {
    }

    display() {
    }

    performFly() {
        this.flyBehavior.fly()
    }

    performQuack() {
        this.quackBehavior.quack()
    }

    setFlyBehavior(flyBehavior: FlyBehavior) {
        this.flyBehavior = flyBehavior
    }

    setQuackBehavior(quackBehavior: QuackBehavior) {
        this.quackBehavior = quackBehavior
    }
}

class RedDuck extends Duck {
    constructor(props) {
        super(props);
        this.flyBehavior = new FlyWithWings()
        this.quackBehavior = new Quack()
    }

}

// 模型鸭
class ModelDuck extends Duck {
	constructor() {
		super();
		// 不会飞
		this.flyBehavior = new FlyNoWay()
		this.quackBehavior = new Quack()
	}
}

// 火箭驱动
class FlyRocketPowered implements FlyBehavior {
	fly() {
		console.log("I'm flying with a rocket!")
	}
}

// 模型鸭
const model: Duck = new ModelDuck()
model.performFly()
model.setFlyBehavior(new FlyRocketPowered())
model.performFly()