class MathUtils {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(MathUtils.add(2, 3)); // 5
console.log(MathUtils.multiply(4, 5)); // 20
const utils = new MathUtils();
// console.log(utils.add(2, 3)); // 错误:utils.add is not a function
class Logger {
constructor() {
if (Logger.instance) {
return Logger.instance;
}
this.logs = [];
Logger.instance = this;
}
static getInstance() {
return new Logger();
}
static log(message) {
const instance = Logger.getInstance();
instance.logs.push({ message, timestamp: Date.now() });
console.log(Log: ${message});
}
static getLogs() {
const instance = Logger.getInstance();
return instance.logs;
}
}
Logger.log("App started");
Logger.log("User logged in");
console.log(Logger.getLogs());
class Shape {
draw() {
throw new Error("子类必须实现 draw 方法");
}
static create(type) {
if (type === "circle") return new Circle();
if (type === "square") return new Square();
throw new Error("未知类型");
}
}
class Circle extends Shape {
draw() {
console.log("绘制圆形");
}
}
class Square extends Shape {
draw() {
console.log("绘制正方形");
}
}
const circle = Shape.create("circle");
const square = Shape.create("square");
circle.draw(); // 绘制圆形
square.draw(); // 绘制正方形
