1. import { Provide } from '@midwayjs/decorator';
  2. import { writeFileSync, readFileSync, existsSync } from 'fs';
  3. const filePath = './todo';
  4. @Provide('TodoListService')
  5. export class TodoListService {
  6. todoList = [];
  7. // 等价于,每次都会创建一个新的实例
  8. constructor() {
  9. this.todoList = []
  10. }
  11. list() {
  12. if (existsSync(filePath)) {
  13. const buffer = readFileSync(filePath);
  14. this.todoList = JSON.parse(buffer.toString());
  15. }
  16. return this.todoList;
  17. }
  18. }

单例模式

  1. import { Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
  2. import { writeFileSync, readFileSync, existsSync } from 'fs';
  3. const filePath = './todo';
  4. @Scope(ScopeEnum.Singleton) // 单例模式
  5. @Provide('TodoListService')
  6. export class TodoListService {
  7. private todoList = [];
  8. list() {
  9. if (existsSync(filePath)) {
  10. const buffer = readFileSync(filePath);
  11. this.todoList = JSON.parse(buffer.toString());
  12. }
  13. return this.todoList;
  14. }
  15. }