如何摆脱状态或依赖的简单原因

时间:2020-09-27 18:22:02

标签: javascript design-patterns

我有一个具有内部状态和公共获取者的类:

function Section() {

  let ls = ['a','b','c','d','e','f'];
  let i = 0;

  this.map = () => ls[i];

  this.changeI = () => i=(i+1)%ls.length;

}

我有一个此类的用户:

function Ground() {

    let section = new Section();
    let mover = new Mover(this);

    let map;

    this.map = () => map;

    this.init = () => {
        map = section.map();
    };


    this.draw = () => {
      console.log(map);
    }
}

和该类别的用户

function Mover(ground) {

  let map = ground.map;


  this.dojob = () => {
    let usemap = map()

    return usemap + 'X';
  }
}

现在,当我调用changeI时,map函数的返回值发生了变化,因此我需要更新用于在Ground函数中绘制地图的变量。 我可以使其成为吸气剂函数,而不是Mover类使用的变量,但是我认为这种方法存在问题,我的意思是有一种更好的方法可以做到这一点,或者我可以摆脱这种内部状态或嵌套现象依赖? 我需要一个尽可能简单的答案。

1 个答案:

答案 0 :(得分:0)

这些类中的每一个都有一个Section的内部实例或另一个访问Section的类的内部实例。因此,您可以调用.map()并始终从Section映射中获取更新的值,而不管i;

请注意,Ground会创建自己的new Section()而不是将现有的Section实例作为参数,因此在此{{1}上调用changeI的唯一方法}实例通过Section

您是否有理由不使用ES6类语法?我将这些内容重写为带有打字稿注释的类(但您可以删除它们)和一些其他更改,我认为这些更改使其更具可读性。

ground.section.changeI()

您可以对其进行测试,看看我们在所有地方都在适当地进行扩展。

class Section {

    private ls = ['a', 'b', 'c', 'd', 'e', 'f'];
    private i = 0;

    public map = (): string => {
        return this.ls[this.i];
    }

    public changeI = (): void => {
        this.i = (this.i + 1) % this.ls.length;
    }

}

class Ground {

    public readonly section = new Section();

    public map = (): string => {
        return this.section.map();
    }

    public draw = (): void => {
        console.log(this.map());
    }

    public createMover = (): Mover => {
        return new Mover(this);
    }
}

class Mover {

    private readonly ground: Ground;

    constructor(ground: Ground) {
        this.ground = ground;
    }

    public dojob = (): string => {
        return this.ground.map() + 'X';
    }
}