设计模式——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());