工厂模式:前端开发者的造轮子规范

74 阅读1分钟

在前端开发中,工厂模式是一种广泛使用的设计模式,旨在创建对象时封装复杂性,将对象类型的决策推迟到子类。简而言之,工厂模式能够帮你以更简洁的方式创建对象

简易工厂模式

classDiagram
Prodect <.. Creator
Prodect : +String name
Prodect: +fn1()
Prodect: +fn2()
class Creator{
+create(name:string):Prodect
}
//简易工厂模式
class Product`{`
    name:string;
    constructor(name:string){
        this.name=name;
    }
    fn1(){
        console.log("产品1")
    }
    fn2(){
        console.log("产品2")
    }
}
class Creator{
    create(name:string):Product{
        return new Product(name);
    }
}
const creator=new Creator();
const p1=-creator.create('p1');
const p2=-creator.create('p2');

标准工厂模式

classDiagram
IProduct <.. Creator
IProduct <|..Product1
IProduct <|..Product2
IProduct : +String name
IProduct: +fn1()
IProduct: +fn2()
class Product1{
+name:string
+f1(name:string):void
+f2(name:string):void
}
class Product2{
+name:string
+f1(name:string):void
+f2(name:string):void
}
class Creator{
+create(type:string,name:string):IProduct
}
<<interface>> IProduct
interface IProduct{
    name:string;
    fn1:()=>void;
    fn2:()=>void;
}
class Product1 implements IProdect{
    name:string;
    constructor(name:string){
        this.name=name;
    }
    fn1(){
        console.log('Product1')
    }
    fn2(){
        console.log('Product1')
    }
}
class Product2 implements IProdect{
    name:string;
    constructor(name:string){
        this.name=name;
    }
    fn1(){
        console.log('Product2')
    }
    fn2(){
        console.log('Product2')
    }
}
class Creator{
    create(type:string,name:string):IProduct{
        if(type==="p1"){
            return new Product1(name);
        }
        if(type==="p2"){
            return new Product2(name);
        }
        throw new Error();
    }
}

使用场景

  1. jQuery $
  2. VUE _createElementVnode
  3. React createElement
//jquery
declare interface Window {
    $:(selector:string)=>JQuery
}
class JQuery{
    selector:string;
    length:number;
    constructor(selsector:string){
        const list=Array.prototype.slice.call(ducument.querySelectorAll(selsector));
        const len=list.length;
        for(let i=0;i<len;i++){
            this[i]=list[i]
        }
        this.selector=selector;
        this.length=len;
    }
    append(ele:HTMLElement):JQuery{
        //...
        return this;
    }
}
//不用工厂模式
const div=new JQuery('div');
//使用工厂模式
window.$=(selector:stirng)=>{
    return new JQuery(selector);
}
const div1=$('div');
// Vue <template>...</template> => render => vnode
<div>
    <span>测试</span>
    <span :id="id" class="test">{msg}</span>
</div>
//React JSX => render => vnode
在render生成vnode中使用到工厂模式