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

2023-12-20 22:57:29

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());

文章来源:https://blog.csdn.net/weixin_46282323/article/details/135117764
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。