// 定义产品接口
interface Product {
  operation(): string
}

// 具体产品类 A
class ConcreteProductA implements Product {
  operation(): string {
    return 'ConcreteProductA operation'
  }
}

// 具体产品类 B
class ConcreteProductB implements Product {
  operation(): string {
    return 'ConcreteProductB operation'
  }
}

// 工厂类
export class Factory {
  createProduct(type: string): Product {
    if (type === 'A') {
      return new ConcreteProductA()
    } else if (type === 'B') {
      return new ConcreteProductB()
    }
    throw new Error('Invalid product type')
  }
}    
  • 原理:工厂模式是一种创建对象的设计模式,它将对象的创建和使用分离。通过一个工厂类来负责创建对象,客户端只需要向工厂类请求所需的对象,而不需要关心对象的具体创建过程。
  • 代码流程
    • Product 接口定义了产品的公共方法 operation()
    • ConcreteProductA 和 ConcreteProductB 是具体的产品类,实现了 Product 接口。
    • Factory 类是工厂类,它有一个 createProduct 方法,根据传入的 type 参数创建不同类型的产品对象。如果传入的 type 无效,则抛出错误。
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐