Skip to content

Instantly share code, notes, and snippets.

@lloydbanks
Created April 26, 2020 13:58
Show Gist options
  • Save lloydbanks/415a05c8d50ad2fc91da1c7d53246f76 to your computer and use it in GitHub Desktop.
Save lloydbanks/415a05c8d50ad2fc91da1c7d53246f76 to your computer and use it in GitHub Desktop.
SOLID
/*
* Single Responsibility Principle
* Принцип единственной ответственности
*
* У класса\модуля должна быть только одна причина для изменения
* или класс должен отвечать только за что-то одно
*/
class News {
constructor(title, text) {
this.title = title
this.text = text
this.modified = false
}
update(text) {
this.text = text
this.modified = true
}
}
class NewsFormatter {
constructor(news) {
this.news = news
}
toHTML() {
const {title, text, modified} = this.news
return `
<div class="news">
<h3>${title}</h3>
<p>${text}</p>
</div>
`
}
toJSON() {
const {title, text, modified} = this.news
return JSON.stringify({title, text, modified}, null, 2)
}
}
const newsData = new News('News title', 'News description')
const news = new NewsFormatter(newsData)
console.log(news.toJSON())
console.log(news.toHTML())
/*
* Open Close Principle
* Принцип открытости-закрытости
*
* какие-то классы должны быть открыты для расширения, но
* закрыты для модификации
*/
class Shape {
getArea() {
throw new Error('Area method should be implemented in child class')
}
}
class Square extends Shape {
constructor(size) {
super()
this.size = size
}
getArea() {
return this.size ** 2
}
}
class Circle extends Shape {
constructor(radius) {
super()
this.radius = radius
}
getArea() {
return (this.radius ** 2) * Math.PI
}
}
class Rect extends Shape {
constructor(width, height) {
super()
this.width = width
this.height = height
}
getArea() {
return this.width * this.height
}
}
class CalcArea {
constructor(shapes = []) {
this.shapes = shapes
}
sum() {
return this.shapes.reduce((acc, shape) => {
acc += shape.getArea()
return acc
}, 0)
}
}
const calc = new CalcArea([
new Square(10),
new Circle(1),
new Circle(5),
new Rect(10, 20)
])
console.log(calc.sum())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment