设计模式——js/ts 实现简单工厂模式

js实现简单工厂模式

// 形状工厂
function ShapeFactory() {
   }

// 添加创建圆形的方法
ShapeFactory.prototype.createCircle = function(radius) {
   
  return new Circle(radius);
};

// 添加创建正方形的方法
ShapeFactory.prototype.createSquare = function(side) {
   
  return new Square(side);
};

// 圆形类
function Circle(radius) {
   
  this.radius = radius;
}

Circle.prototype.getArea = function() {
   
  return Math.PI * this.radius * this.radius;
};

// 正方形类
function Square(side) {
   
  this.side = side;
}

Square.prototype.getArea = function() {
   
  return this.side * this.side;
};

// 使用简单工厂创建形状对象
const factory = new ShapeFactory();

const myCircle = factory.createCircle(5);
console.log("圆形面积:", myCircle.getArea());

const mySquare = factory.createSquare(4);
console.log("正方形面积:", mySquare.getArea());

ts实现简单工厂模式

// 形状接口
interface Shape {
   
  getArea(): number;
}

// 圆形类
class Circle implements Shape {
   
  constructor(private radius: number) {
   }

  getArea(): number {
   
    return Math.PI * this.radius * this.radius;
  }
}

// 正方形类
class Square implements Shape {
   
  constructor(private side: number) {
   }

  getArea(): number {
   
    return this.side * this.side;
  }
}

// 形状工厂类
class ShapeFactory {
   
  createCircle(radius: number): Circle {
   
    return new Circle(radius);
  }

  createSquare(side: number): Square {
   
    return new Square(side);
  }
}

// 使用简单工厂创建形状对象
const factory = new ShapeFactory();

const myCircle = factory.createCircle(5);
console.log("圆形面积:", myCircle.getArea());

const mySquare = factory.createSquare(4);
console.log("正方形面积:", mySquare.getArea());

相关推荐

  1. 设计模式——js/ts 实现简单工厂模式

    2023-12-22 04:22:02       53 阅读
  2. 设计模式简单工厂模式

    2023-12-22 04:22:02       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-22 04:22:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-22 04:22:02       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-22 04:22:02       87 阅读
  4. Python语言-面向对象

    2023-12-22 04:22:02       96 阅读

热门阅读

  1. springboot实现netty的websocket服务端与客户端

    2023-12-22 04:22:02       56 阅读
  2. Mysql的基础问题原理

    2023-12-22 04:22:02       59 阅读
  3. 灰度化、二值化、边缘检测、轮廓检测

    2023-12-22 04:22:02       60 阅读
  4. vue 响应式页面使用transform实现

    2023-12-22 04:22:02       74 阅读
  5. springboot项目0-1之mybatis

    2023-12-22 04:22:02       71 阅读
  6. Linux DISK赛题配置

    2023-12-22 04:22:02       59 阅读