ts 适配器模式学习

428 阅读2分钟

适配器模式

应用场景:

  • 系统需要使用现有的类,但是这些类的接口不符合系统的需要。
  • 需要建立一个重复使用的类,使一个彼此没有太大联系的类,能在一起工作。

感受:几乎没看懂,直接来看例子, 例子1(日志系统适配)(这个没看懂也没关系):

// 定义接口
interface Logger {
    info(message: string): Promise<void>
}

interface CloudLogger {
    sendToServer(message: string, type: string): Promise<void>
}
// 日志实现类
class AliLogger implements CloudLogger {
    public async sendToServer(message: string, type: string): Promise<void> {
        console.log(message)
        console.log(`This Message was saved with AliLogger`)
    }
}

// 适配器
class CloudLoggerAdapter implements Logger {
    protected cloudLogger: CloudLogger
    constructor(cloudLogger: CloudLogger) {
        this.cloudLogger = cloudLogger
    }
    public async info(message: string): Promise<void> {
        await this.cloudLogger.sendToServer(message, 'info')
    }

}

// 通知服务类
class NotificationService {
    protected logger: Logger;
    constructor(logger: Logger) {
        this.logger = logger
    }
    public async send(message: string): Promise<void> {
        await this.logger.info(`Notification sended:${message}`)
    }
}

// 使用
(async () => {
    const aliLogger = new AliLogger()
    const cloudLoggerAdapter = new CloudLoggerAdapter(aliLogger)
    const notificationService = new NotificationService(cloudLoggerAdapter)
    await notificationService.send(`Hello Kakuqo, To Cloud`)
})()

接下来来看例子2(还没看懂我也没办法):

// 职业:护士,会一个制服play的技能,rules指客人的需求
interface Nurse {
    uniformPlay(rules: string): Promise<void>
}
// 职业:老师,回一个教师play的技能,rules指客人的需求,wear指表演时穿的衣服
interface Teacher {
    teachPlay(rules: string, wear: string): Promise<void>
}

//职业:小姐姐,都是从老师转行而来,必须会一个teachPlay的技能
class LittleSister implements Teacher {
    public async teachPlay(rules: string, wear: string): Promise<void> {
        console.log('小姐姐教你教室play哦')
    }
}
//适配器: 学校,就是将护士培养成小姐姐的机构,这个小姐姐会teachPlay这么一个节能,并且统一穿着裙子skirt,毕业后必须都会一个支付表演的技能
class SchoolAdapter implements Nurse {
    protected students: Teacher
    constructor(students: Teacher) {
        this.students = students
    }
    public async uniformPlay(rules: string): Promise<void> {
        await this.students.teachPlay(rules, 'skirt')
    }
}

// 按摩行业工作,这些小姐姐必须都是从护士转行来的,这个工作需要会洗浴(bath)一个技能,
class Work {
    protected nurse: Nurse;
    constructor(nurse: Nurse) {
        this.nurse = nurse
    }
    public async bath(message: string) {
        await this.nurse.uniformPlay(`我要制服表演了`)
    }
}

(async () => {
    const xiaojiejie = new LittleSister()
    const schoolAdapter = new SchoolAdapter(xiaojiejie)
    const work = new Work(schoolAdapter)
    await work.bath('我要洗澡了')
})()
// 就是有一个小姐姐(她之前是做老师的),她要去做按摩行业工作,她必须要经过学校的培训,掌握一项洗澡的技能后才能进行按摩工作

总结:就是使用一个适配器Adapter,将不同的类,能在一起工作(将原来当老师的变成一个会洗浴,会制服表演的小姐姐)