typescript面向对象小例子

132 阅读1分钟

面向对象模式实现业务逻辑。 工厂模式实现各种类型元数据的创建。

单例模式,MobileDesignerDom基类仅实现创建功能。

export class MobileDesignerDom {
    domFactory: IDomFactory;
    create(type: DgControlType): IMobileDesignerDom {
        return this.domFactory.create(type);
    };
}

基类中定义一个专门创建元数据的工厂接口IDomFactory,工厂负责实际的创建工作。

export interface IDomFactory {
    create: (value?: any) => any
}

各类元数据继承MobileDesignerDom基类,比如Button类型的。

export class ButtonFactory extends MobileDesignerDom {
    constructor() {
        super();
        this.domFactory = new CreateButtonFactory();
    }
}

Input类中为了低耦合,定义了Input自己的工厂类,该工厂类专门用于创建元数据一项工作。 这样避免了重写create方法,也容易Input类的扩展,符合开放封闭原则。

export class CreateButtonFactory implements IDomFactory {
    create(type: DgControlType): IMobileDesignerDom {
        // id
        const id = Guid.newGuid().slice(0, 6) + type;
        return {
            id,
            type,
            title: type,
            text: '按钮',
            appearance: null,
            size: null,
            disabled: false,
            icon: null,
            iconPosition: null,
            seperate: true,
            textAligment: 'center',
            click: null,
            template: null,
            visible: true
        }
    };
}

其他类的创建元数据方式同上。

这样下来结构清晰,但是也有不足的地方。一旦元数据种类数量过多,要创建很多类和工厂,增加了重复工作。如果有折中的方式,请各位大神指教。