import { Provide } from '@midwayjs/decorator';
import { writeFileSync, readFileSync, existsSync } from 'fs';
const filePath = './todo';
@Provide('TodoListService')
export class TodoListService {
todoList = [];
// 等价于,每次都会创建一个新的实例
constructor() {
this.todoList = []
}
list() {
if (existsSync(filePath)) {
const buffer = readFileSync(filePath);
this.todoList = JSON.parse(buffer.toString());
}
return this.todoList;
}
}
单例模式
import { Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
import { writeFileSync, readFileSync, existsSync } from 'fs';
const filePath = './todo';
@Scope(ScopeEnum.Singleton) // 单例模式
@Provide('TodoListService')
export class TodoListService {
private todoList = [];
list() {
if (existsSync(filePath)) {
const buffer = readFileSync(filePath);
this.todoList = JSON.parse(buffer.toString());
}
return this.todoList;
}
}