#跟着坚果学鸿蒙#鸿蒙next ArkTs工厂模式实现
·
在ArkTS中实现工厂模式,主要通过抽象接口与具体实现的分离来达成对象创建的灵活控制,以下是核心实现方式及代码示例:
一、工厂模式核心要素
- 抽象产品接口
- 定义产品通用方法,如:
typescriptCopy Codeinterface Shape {
draw(): void;
}
- 具体产品实现
- 实现接口的不同子类:
typescriptCopy Codeclass Circle implements Shape {
draw(): void {
console.log("绘制圆形")
}
}
class Rectangle implements Shape {
draw(): void {
console.log("绘制矩形")
}
}
- 工厂类
- 封装对象创建逻辑:
typescriptCopy Codeclass ShapeFactory {
static createShape(type: string): Shape | null {
switch(type) {
case 'circle':
return new Circle();
case 'rectangle':
return new Rectangle();
default:
return null;
}
}
}
二、客户端调用示例
typescriptCopy Code// 创建圆形对象
const circle = ShapeFactory.createShape('circle');
circle?.draw(); // 输出:绘制圆形
// 创建矩形对象
const rect = ShapeFactory.createShape('rectangle');
rect?.draw(); // 输出:绘制矩形
- 设计优势
- 业务逻辑与对象创建解耦,提升代码扩展性18
- 符合开闭原则,新增产品类型无需修改工厂核心逻辑3
四、应用场景建议
- 需要统一管理多个相似对象的创建过程时
- 系统需支持多套UI组件库的动态切换
- 第三方插件扩展场景下的对象实例化6
代码维护提示
推荐结合@Builder
装饰器实现链式调用,提升工厂类可读性5。对于复杂对象构建,可参考建造者模式进行组合优化5。
完整代码
// 抽象产品接口
interface Shape {
draw(): void;
}
// 具体产品实现类
class Circle implements Shape {
draw(): void {
console.log("绘制圆形 ○");
}
}
class Rectangle implements Shape {
draw(): void {
console.log("绘制矩形 ▭");
}
}
// 工厂类
class ShapeFactory {
static createShape(type: string): Shape | null {
switch(type) {
case 'circle':
return new Circle();
case 'rectangle':
return new Rectangle();
default:
console.error("不支持的图形类型");
return null;
}
}
}
// 客户端调用示例
@Entry
@Component
struct FactoryExample {
build() {
Column() {
Button('创建圆形')
.onClick(() => {
const shape = ShapeFactory.createShape('circle');
shape?.draw();
})
Button('创建矩形')
.onClick(() => {
const shape = ShapeFactory.createShape('rectangle');
shape?.draw();
})
}
.width('100%')
.height('100%')
}
}
更多推荐
所有评论(0)