Skip to content

Instantly share code, notes, and snippets.

@balkhaev
Last active October 26, 2018 12:06
Show Gist options
  • Save balkhaev/fd2e84900eab15f4fa6089eaf3eab7b7 to your computer and use it in GitHub Desktop.
Save balkhaev/fd2e84900eab15f4fa6089eaf3eab7b7 to your computer and use it in GitHub Desktop.
Инкапсуляция против абстракции
/**
* Кейс когда лучше инкапсуляция.
* Необходимо создать
*/
// Инкапсуляция
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
say(text = '') {
return `${this.name}: ${text}`;
}
log() {
console.log(this.say(`level ${this.level}`));
}
}
class Hunter extends Hero {
constructor(name, level, arrow) {
super(name, level);
this.arrow = arrow;
}
shot() {
return this.say(`shot arrow ${this.arrow}`);
}
}
class Druid extends Hero {
constructor(name, level, spell) {
super(name, level);
this.spell = spell;
}
cast() {
return this.say(`casting ${this.spell}`);
}
}
const musya = new Druid('musya', 10, 'Бросок насвая');
const pusya = new Hunter('pusya', 10, 'Горящая стрела');
// Абстракция
function hero(name, level) {
const say = (text) => `${name}: ${text}`;
return {
say,
log() {
console.log(say(`level ${level}`));
},
}
}
function hunter(name, level, arrow) {
const char = hero(name, level);
return {
say: char.say,
log: char.log,
shot: () => char.say(`shot arrow ${arrow}`),
}
}
function druid(name, level, spell) {
const char = hero(name, level);
return {
say: char.say,
log: char.log,
cast: () => char.say(`casting ${spell}`),
}
}
const vaflya = druid('vaflya', 25, 'Рунический пердеж');
const pechka = hunter('pechka', 15, 'Стрела богини лун');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment