SOLID
The Single Responsibility Principle
Templates
- Шаблон «Выделение класса»
- Шаблон «Фасад»
- Шаблон «Proxy»
const circle = (radius) => {
const proto = {
type: 'Circle'
}
return Object.assign(Object.create(proto), {radius})
}
const square = (length) => {
const proto = {
type: 'Square'
}
return Object.assign(Object.create(proto), {length})
}
const areaCalculator = (s) => {
const proto = {
sum() {
// logic to sum
},
output () {
return `
<h1>
Sum of the areas of provided shapes:
${this.sum()}
</h1>
}
}
return Object.assign(Object.create(proto), {shapes: s})
}
const shapes = [
circle(2),
square(5),
square(6)
]
const areas = areaCalculator(shapes)
const output = sumCalculatorOputter(areas)
console.log(output.JSON())
console.log(output.HAML())
console.log(output.HTML())
console.log(output.JADE())
Open-closed Principle
sum () {
const area = []
for (shape of this.shapes) {
if (shape.type === 'Square') {
area.push(Math.pow(shape.length, 2)
} else if (shape.type === 'Circle') {
area.push(Math.PI * Math.pow(shape.length, 2)
}
}
return area.reduce((v, c) => c += v, 0)
}
interface ShapeInterface {
area(): number
}
class Circle implements ShapeInterface {
let radius: number = 0
constructor (r: number) {
this.radius = r
}
public area(): number {
return MATH.PI * MATH.pow(this.radius, 2)
}
}
Liskov substitution principle
const volumeCalculator = (s) => {
const proto = {
type: 'volumeCalculator'
}
const areaCalProto = Object.getPrototypeOf(areaCalculator())
const inherit = Object.assign({}, areaCalProto, proto)
return Object.assign(Object.create(inherit), {shapes: s})
}
Interface segregation principle
const shapeInterface = (state) => ({
type: 'shapeInterface',
area: () => state.area(state),
volume: () => state.volume(state)
})
What is volume of a square?
const shapeInterface = (state) => ({
type: 'shapeInterface',
area: () => state.area(state)
})
const solidShapeInterface = (state) => ({
type: 'solidShapeInterface',
volume: () => state.volume(state)
})
const cubo = (length) => {
const proto = {
length,
type : 'Cubo',
area : (args) => Math.pow(args.length, 2),
volume : (args) => Math.pow(args.length, 3)
}
const basics = shapeInterface(proto)
const complex = solidShapeInterface(proto)
const composite = Object.assign({}, basics, complex)
return Object.assign(Object.create(composite), {length})
}
Dependency inversion principle
public class Reporter
{
public void SendReports()
{
var reportBuilder = new ReportBuilder();
IList<Report> reports = reportBuilder.CreateReports();
if (reports.Count == 0)
throw new NoReportsException();
var reportSender = new EmailReportSender();
foreach (Report report in reports)
{
reportSender.Send(report);
}
}
}
SOLID
By Vladimir
SOLID
- 111