工厂模式把创建对象或者实例的方法进行统一封装处理,不再需要每次自己创建。
一般遇到new class的场景,可以尝试考虑使用工厂模式。
代码演示:
interface IPerson { name: string; speak(): void; } class Teacher implements IPerson { constructor(public name: string) {} speak() { console.log(`${this.name}老师说话`); } } class Student implements IPerson { constructor(public name: string) {} speak() { console.log(`${this.name}同学说话`); } } class Parent implements IPerson { constructor(public name: string) {} speak() { console.log(`${this.name}家长说话`); } } function create(type: string, name: string): IPerson { if (type === 'student') { return new Student(name); } if (type === 'teacher') { return new Teacher(name); } if (type === 'parent') { return new Parent(name); } throw new Error('输入的参数不正确'); } const p1 = create('student', '小明'); const p2 = create('teacher', '王皓'); const p3 = create('parent', '田雨'); p1.speak(); p2.speak(); p3.speak();
UML类图:
jQuery
如下伪代码示例:
// 扩展window属性 declare interface Window { $: (selector: string) => JQuery; } class JQuery { constructor(selector: string) { const arr: any[] = [...document.querySelectorAll(selector)]; arr.forEach((item, index) => { // @ts-ignore this[index] = item; }); } removeClass() { //... return this; } addClass() { //... return this; } } function $(selector: string) { return new JQuery(selector); } window.$ = $;