核心词
解决对象的创建问题。
模式 UML 图![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/239a89d7708eee376a021b9251a18bc5.png#pic_center)
实例代码(TypeScript)
// 运算类
class Operation {
protected _numberA: number;
protected _numberB: number;
public getNmberA(): number {
return this._numberA;
}
public getNumberB(): number {
return this._numberB;
}
public setNumberA(val: number): void {
this._numberA = val;
}
public setNumberB(val: number): void {
this._numberB = val;
}
public GetResult(): number {
const result: number = 0;
return result;
}
}
// 加法类
class OperationAdd extends Operation {
public GetResult(): number {
let result = 0;
result = this._numberA + this._numberB;
return result;
}
}
// 减法类
class OperationSub extends Operation {
public GetResult(): number {
let result = 0;
result = this._numberA - this._numberB;
return result;
}
}
// 乘法类
class OperationMul extends Operation {
public GetResult(): number {
let result = 0;
result = this._numberA * this._numberB;
return result;
}
}
// 除法类
class OperationDiv extends Operation {
public GetResult(): number {
let result = 0;
if (!this._numberB) {
throw new Error("除数不能为0");
} else {
result = this._numberA / this._numberB;
}
return result;
}
}
class OperationFactory {
public static createOperation(operate: string): Operation {
let oper;
switch (operate) {
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
}
}
const oper = OperationFactory.createOperation("+");
oper.setNumberA(1);
oper.setNumberB(2);
const result = oper.GetResult();
总结
从上述例子我们可以看到,我们的计算业务里面包含了加、减、乘和除的业务实例,而这些实例的功能和创建都是一样的,只是业务核心处理不一样,所以我们采用建东工厂模式的话,就可以把这些业务代码集中起来进行管理和维护。
所以简单工厂模式的核心思想就是把业务功能全部集中到工厂中,通过工厂创建对应的业务实例来实现业务功能,而这些业务功能的共同点都是业务功能类似、输入和输出参数保持一致这样才行。