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