我学会了,策略模式

简介: 策略模式属于行为型模式,这个类型的设计模式总结出了 类、对象之间的经典交互方式,将类、对象的行为和使用解耦了,花式的去使用对象的行为来完成特定场景下的功能。

前言

策略模式属于行为型模式,这个类型的设计模式总结出了 类、对象之间的经典交互方式,将类、对象的行为和使用解耦了,花式的去使用对象的行为来完成特定场景下的功能。

策略模式

使用场景:这种模式是将一个个算法、行为封装起来,然后通过切换的方式去使用这些算法、行为,最后进行最终的运算、执行。这种模式在生活种比较常见,比如 不同接口的螺丝刀、不同风格的衣服、不同款式的显示器等等,非常多。

理解:这是一种类、对象之间的经典交互方式,将类、对象的行为和使用解耦了,很常见。使用这种设计模式的前提是,要先定义好功能接口,这样切换不同算法、行为时才能正常运行。这种设计模式本身就是为了减少过多的 if else冗余,所以功能接口的设计很重要,比如借助Map这样的数据结构,那么就更加方便了,甚至都不需要去封装类,直接封装成函数放入map中,根据不同的key来使用相应的函数。

namespace action_mode_03 {

    // 接口
    interface IPlay {
        buy(price: number): number
        run(): string

    }


    class Computer implements IPlay {
        price: number = 6000

        buy(price: number): number {
            // 打六折
            const finalPrice = this.price * 0.6
            return price  - finalPrice
        }

        run(): string {
            return '计算机开机 =======> 欢迎使用 windows10'
        }

    }

    class Pad implements IPlay {
        price: number = 10000

        run(): string {
            return '平板开机 =======> 欢迎使用 华为平板'
        }

        buy(price: number): number {
            // 打七五折
            const finalPrice = this.price * 0.75
            return price - finalPrice
        }
    }


    class TV implements IPlay {
        price: number = 3000

        run(): string {
            return '电视开机 =======> 欢迎使用 小米电视'
        }

        buy(price: number): number {
            // 打8折
            const finalPrice = this.price * 0.8
            return price - finalPrice
        }
    }

    // 操作类
    class Student {

        money: number

        constructor(money: number) {
            this.money = money
        }

        get(strategyType: StrategyType) {
            const strategy = new strategyList[strategyType]
            const result = strategy.buy(this.money)
            if (result < 0) {
                return '钱不够,购买失败'
            }
            return strategy.run()
        }
    }

    // 策略的枚举
    enum StrategyType {
        Computer,
        Pad,
        TV,
    }

    // 策略的定义
    const strategyList = {
        [StrategyType.Computer]: Computer,
        [StrategyType.Pad]: Pad,
        [StrategyType.TV]: TV,
    }

    const xiaoming = new Student(5000)

    console.log("小明买计算机", xiaoming.get(StrategyType.Computer))
    console.log("小明买平板电脑", xiaoming.get(StrategyType.Pad))
    console.log("小明买液晶电视机", xiaoming.get(StrategyType.TV))
}

目录
相关文章
|
3月前
|
算法 数据安全/隐私保护
行为型 策略模式
行为型 策略模式
24 1
|
12月前
|
设计模式 算法 Java
什么场景要使用策略模式,什么场景不能使用?
如果,让我来设计,我最先想到的就是策略模式。另外,我把往期面试题解析的配套文档我已经准备好,想获得的可以在我的煮叶简介中找到。那么什么场景要使用策略模式,什么场景又不应该使用策略模式呢?我们可以先来看官方对策略模式的定义。
136 0
|
前端开发
策略模式
策略模式
70 0
|
设计模式 算法
策略模式详细介绍
策略模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列的算法,并将每个算法封装到具有共同接口的独立类中,使得它们可以互相替换。策略模式可以让算法的变化独立于使用它的客户端。
102 0
|
算法 测试技术 C#
C#策略模式
C#策略模式
53 0
|
设计模式 前端开发
关于策略模式我所知道的
关于策略模式我所知道的
74 0
|
算法 程序员 开发工具
简单说说我对策略模式的了解
简单说说我对策略模式的了解
75 0
|
设计模式 算法 安全