// @dynamic export abstract class LoginType { static USERNAME = '0'; static MOBILE = '1'; static _nullObj = {'userName': '', 'mobile': ''}; // Use protected, to do not implementing getter/setter protected _accessNo: string; protected constructor(accessNo: string) { this._accessNo = accessNo; } static getNullObj() { // it may be a bug; JSON.parse(JSON.stringify( return JSON.parse(JSON.stringify(this._nullObj)); } abstract getTypeCode(); abstract toJSON(); } // 将accessNo 封装为userName export class UserName extends LoginType { constructor(userName: string) { super(userName); } get userName(): string { return this._accessNo; } set userName(value: string) { this._accessNo = value; } getTypeCode() { return LoginType.USERNAME; } toJSON() { const json = LoginType.getNullObj(); json.userName = this._accessNo; return json; } SimpleJSON() { return {userName: this._accessNo}; } } // mobile 封装为userName export class Mobile extends LoginType { constructor(mobile: string) { super(mobile); } get mobile(): string { return this._accessNo; } set mobile(value: string) { this._accessNo = value; } // toJSON() { return LoginType.getNullObj().mobile = this._accessNo; } toJSON() { const json = LoginType.getNullObj(); json.mobile = this._accessNo; return json; } SimpleJSON() { return {mobile: this._accessNo}; } getTypeCode() { return LoginType.MOBILE; } } class NullLogin extends LoginType { constructor() { super('hz'); } private static singleton: NullLogin; public static getInstance(): NullLogin { if (!NullLogin.singleton) { NullLogin.singleton = new NullLogin(); } return NullLogin.singleton; } getTypeCode() { } toJSON() { return LoginType.getNullObj(); } SimpleJSON() { return ''; } } // sample: str=> LoginTypeFactory.createLogObj(str).toJSON() // @dynamic export class LoginTypeFactory { // fixme it may be a better static mobileRule = /^\d+$/; static createLogObj(logStr: string) { if (this.IsMobile(logStr)) return LoginTypeFactory.CreateMobile(logStr); if (this.IsNull(logStr)) return LoginTypeFactory.CreateNull(); return LoginTypeFactory.CreateUserName(logStr); } static CreateUserName(userName: string) { return new UserName(userName); } static CreateMobile(mobile: string) { return new Mobile(mobile); } static IsMobile(testStr: string) { return this.mobileRule.test(testStr); } static IsNull(testStr: string) { return testStr === '' || testStr === 'null' || testStr === null; } public static CreateNull() { return NullLogin.getInstance(); } }