Показать сообщение отдельно
  #1 (permalink)  
Старый 11.04.2024, 17:59
Аспирант
Отправить личное сообщение для firep91613 Посмотреть профиль Найти все сообщения от firep91613
 
Регистрация: 24.10.2023
Сообщений: 55

ООП. Нужен совет.
Делаю рисовалку на SVG. Сейчас у меня в файле класса рисовалки почти 300 строк кода. Я уже путаюсь что и где. Решил сделать отдельные классы для каждого элемента. Думаю, еще классы раскидать по разным файлам. До этого эти классы были методами класса рисовалки.

Пример:
class Circle {
  constructor(x, y, r = 20, c = '#7F6565') {
    this.x = x;
    this.y = y;
    this.radius = r;
    this.color = c;
  }

  create() {
    const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    circle.setAttribute('r', this.radius);
    circle.setAttribute('cx', this.x);
    circle.setAttribute('cy', this.y);
    circle.setAttribute('fill', this.color);
    circle.setAttribute('stroke-width', 1);
    return circle;
  }
}

class Line {
  constructor(x1, y1, x2, y2, c = 'black') {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
    this.color = c;
  }

  create() {
    const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    line.setAttribute('x1', this.x1);
    line.setAttribute('y1', this.y1);
    line.setAttribute('x2', this.x2);
    line.setAttribute('y2', this.y2);
    line.setAttribute('stroke', this.color);
    return line;
  }
}

class Arrow {
  constructor(x1, y1, x2, y2, c = 'black') {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
    this.color = c;
  }

  create() {
    const lineLength = (Math.abs(this.x1 - this.x2) ** 2 + Math.abs(this.y1 - this.y2) ** 2) ** 0.5;
    const cos = (this.x2 - this.x1) / lineLength;

    const angle = (this.y1 >= this.y2) ? Math.acos(cos) : Math.PI + (Math.PI - Math.acos(cos));
    const arrowLength = 15;
    const arrowAngle = Math.PI / 12;

    const moreAngle = angle + arrowAngle;
    const moreAngleX = this.x2 - Math.cos(moreAngle) * arrowLength;
    const moreAngleY = this.y2 + Math.sin(moreAngle) * arrowLength;
    const moreAngleLine = new Line(this.x2, this.y2, moreAngleX, moreAngleY);

    const lessAngle = angle - arrowAngle;
    const lessAngleX = this.x2 - Math.cos(lessAngle) * arrowLength;
    const lessAngleY = this.y2 + Math.sin(lessAngle) * arrowLength;
    const lessAngleLine = new Line(this.x2, this.y2, lessAngleX, lessAngleY);

    return {
      moreAngleLine: moreAngleLine.create(),
      lessAngleLine: lessAngleLine.create()
    };
  }
}

На сколько оправдан такой код с точки зрения ООП? И как лучше сделать?
Ответить с цитированием