SlideShare a Scribd company logo
1 of 46
2
https://en.wikipedia.org/wiki/Object-oriented_programming
https://ko.wikipedia.org/wiki/객체_지향_프로그래밍
https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
https://en.wikipedia.org/wiki/This_(computer_programming)#Open_recursion
https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)
https://en.wikipedia.org/wiki/Delegation_(computing)
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
Ch.01
5
 Combination of recursion and late binding
override 아니에요 ?
 No, no, no. Recursion and late binding.
그래도 그냥 함수 override인데…
6
interface FileItem {
path: string;
contents: string[];
}
class FileReader {
getFiles(path: string, depth: number = 0) {
var fileTree = [];
var files = fs.readdirSync(path);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var stats = fs.statSync(file);
var fileItem;
if (stats.isDirectory()) {
// Add directory and contents
fileItem = {
path: file,
contents: this.getFiles(file, (depth + 1))
};
} else {
// Add file
fileItem = {
path: file,
contents: [] };
}
fileTree.push(fileItem);
}
return fileTree;
}
}
class LimitedFileReader extends FileReader {
constructor(public maxDepth: number) {
super();
}
getFiles(path: string, depth = 0) {
if (depth > this.maxDepth) {
return [];
}
return super.getFiles(path, depth);
}
}
// instatiating an instance of LimitedFileReader
var fileReader = new LimitedFileReader(1);
// results in only the top level, and one additional level being read
var files = fileReader.getFiles('path');
7
 Private 제한자를 사용해 변수, 함수를 외부로부터 숨김
 외부에 알리고 싶지 않은 것을 숨길 수 있음
 외부에서 몰라도 되는 것을 숨기는 것은 추상화(Abstraction)
추상화나 캡슐화나… 내가 보기엔 다 거서 건데…
8
class Totalizer {
private total = 0;
private taxRateFactor = 0.2;
addDonation(amount: number) {
if (amount <= 0) {
throw new Error('Donation exception');
}
var taxRebate = amount * this.taxRateFactor;
var totalDonation = amount + taxRebate;
this.total += totalDonation;
}
getAmountRaised() {
return this.total;
}
}
var totalizer = new Totalizer();
totalizer.addDonation(100.00);
var fundsRaised = totalizer.getAmountRaised();
// 120
console.log(fundsRaised);
9
 Wrapper class로 원래 class를 감싸는 형태
 상속관계 (is a)가 아닌 경우의 좋은 대안
 코드 재사용성 측면에 있어서 가장 유용한 개념
10
 Delegation : Has A
 Ingeritance : Is A
11
interface ControlPanel {
startAlarm(message: string): any;
}
interface Sensor {
check(): any;
}
class MasterControlPanel {
private sensors: Sensor[] = [];
constructor() {
// Instantiating the delegate HeatSensor
this.sensors.push(new HeatSensor(this));
}
start() {
for (var i= 0; i < this.sensors.length; i++) {
// Calling the delegate
this.sensors[i].check();
}
window.setTimeout(() => this.start(), 1000);
}
startAlarm(message: string) {
console.log('Alarm! ' + message);
}
}
class HeatSensor {
private upperLimit = 38;
private sensor = {
read: function() { return Math.floor(Math.random() * 100); }
};
constructor(private controlPanel: ControlPanel) {
}
check() {
if (this.sensor.read() > this.upperLimit) {
// Calling back to the wrapper
this.controlPanel.startAlarm('Overheating!');
}
}
}
var cp = new MasterControlPanel();
cp.start();
12
 같은 함수 시그너쳐를 여러가지로 다르게 구현
 Any structure with many similar structures
13
interface Vehicle {
moveTo(x: number, y: number);
}
class Car implements Vehicle {
moveTo(x: number, y: number) {
console.log('Driving to ' + x + ' ' + y);
}
}
class SportsCar extends Car {
}
class Airplane {
moveTo(x: number, y: number) {
console.log('Flying to ' + x + ' ' + y);
}
}
function navigate(vehicle: Vehicle) {
vehicle.moveTo(59.9436499, 10.7167959);
}
var airplane = new Airplane();
navigate(airplane);
var car = new SportsCar();
navigate(car);
15
16
http://blog.cleancoder.com
단일 책임의 원칙
클래스는 오직 한가지 작업만 수행해야 하며,
한 가지 이유에 의해서만 변경되어야 함.
17
class Movie {
private db: DataBase;
constructor(private title: string, private year: number) {
this.db = DataBase.connect('user:pw@mydb', ['movies']);
}
getTitle() {
return this.title + ' (' + this.year + ')';
}
save() {
this.db.movies.save({ title: this.title, year: this.year });
}
}
18
class Movie {
constructor(private title: string, private year: number) {
}
getTitle() {
return this.title + ' (' + this.year + ')';
}
}
class MovieRepository {
private db: DataBase;
constructor() {
this.db = DataBase.connect('user:pw@mydb', ['movies']);
}
save(movie: Movie) {
this.db.movies.save(JSON.stringify(movie));
}
}
// Movie
var movie = new Movie('The Internship', 2013);
// MovieRepository
var movieRepository = new MovieRepository();
movieRepository.save(movie);
19
개방/폐쇄 원칙
확장에 대해서는 개방적이어여 하고,
수정에 대해서는 폐쇄적이어야 한다.
20
class RewardPointsCalculator {
getPoints(transactionValue: number) {
// 4 points per whole dollar spent
return Math.floor(transactionValue) * 4;
}
}
class DoublePointsCalculator extends RewardPointsCalculator {
getPoints(transactionValue: number) {
var standardPoints = super.getPoints(transactionValue);
return standardPoints * 2;
}
}
var pointsCalculator = new DoublePointsCalculator();
alert(pointsCalculator.getPoints(100.99));
21
리스코프 치환 원칙
S가 T의 하위속성이라면 프로그램의 변경없이
T의 객체를 S로 교체(치환)할 수 있어야 한다.
Data Abstraction and Hireachy, 1998 - Babara Liskov
22
출처 : C#으로 배우는 적응형 코드
23
인터페이스 분리 원칙
인터페이스를 최대한 작게 만드는 것이
여러가지 기능을 하는 인터페이스 하나보다 더 좋다.
24
interface Printer {
copyDocument();
printDocument(document: Document);
stapleDocument(document: Document, tray: number);
}
interface Printer {
printDocument(document: Document);
}
interface Stapler {
stapleDocument(document: Document, tray: number);
}
interface Copier {
copyDocument();
}
class SimplePrinter implements Printer {
printDocument(document: Document) {
//...
}
}
class SuperPrinter implements Printer, Stapler, Copier {
printDocument(document: Document) {
//...
}
copyDocument() {
//...
}
stapleDocument(document: Document, tray: number) {
//...
}
}
25
의존성 역주입 원칙
직접적인 의존을 피하고,
인터페이스에 의존하라.
26
class LightSwitch {
private isOn = false;
constructor(private light: Light) {
}
onPress() {
if (this.isOn) {
this.light.switchOff();
this.isOn = false;
} else {
this.light.switchOn();
this.isOn = true;
}
}
}
interface LightSource {
switchOn();
switchOff();
}
class Light {
switchOn() {
//...
}
switchOff() {
//...
}
}
28
29
전략 패턴
30
추상 팩토리 패턴
31
interface WheelCleaning {
cleanWheels(): void;
}
class BasicWheelCleaning implements WheelCleaning {
cleanWheels() {
console.log('Soaping Wheel');
console.log('Brushing wheel');
}
}
class ExecutiveWheelCleaning extends
BasicWheelCleaning {
cleanWheels() {
super.cleanWheels();
console.log('Waxing Wheel');
console.log('Rinsing Wheel');
}
}
interface BodyCleaning {
cleanBody(): void;
}
class BasicBodyCleaning implements BodyCleaning {
cleanBody() {
console.log('Soaping car');
console.log('Rinsing Car');
}
}
class ExecutiveBodyCleaning extends BasicBodyCleaning
{
cleanBody() {
super.cleanBody();
console.log('Waxing car');
console.log('Blow drying car');
}
}
32
class CarWashProgram {
constructor(private washLevel: number) {
}
runWash() {
var wheelWash: WheelCleaning;
var bodyWash: BodyCleaning;
switch (this.washLevel) {
case 1:
wheelWash = new BasicWheelCleaning();
wheelWash.cleanWheels();
bodyWash = new BasicBodyCleaning();
bodyWash.cleanBody();
break;
case 2:
wheelWash = new BasicWheelCleaning();
wheelWash.cleanWheels();
bodyWash = new ExecutiveBodyCleaning();
bodyWash.cleanBody();
break;
case 3:
wheelWash = new ExecutiveWheelCleaning();
wheelWash.cleanWheels();
bodyWash = new ExecutiveBodyCleaning();
bodyWash.cleanBody();
break;
}
}
}
33
interface ValetFactory {
getWheelCleaning() : WheelCleaning;
getBodyCleaning() : BodyCleaning;
}
class SilverWashFactory implements ValetFactory {
getWheelCleaning() {
return new BasicWheelCleaning();
}
getBodyCleaning() {
return new ExecutiveBodyCleaning();
}
}
class GoldWashFactory implements ValetFactory {
getWheelCleaning() {
return new ExecutiveWheelCleaning();
}
getBodyCleaning() {
return new ExecutiveBodyCleaning();
}
}
class BronzeWashFactory implements ValetFactory {
getWheelCleaning() {
return new BasicWheelCleaning();
}
getBodyCleaning() {
return new BasicBodyCleaning();
}
}
34
class CarWashProgram {
constructor(private cleaningFactory: ValetFactory) {
}
runWash() {
var wheelWash = this.cleaningFactory.getWheelCleaning();
wheelWash.cleanWheels();
var bodyWash = this.cleaningFactory.getBodyCleaning();
bodyWash.cleanBody();
}
}
36
37
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
})
});
}
38
class Sings {
sing() {
console.log('Singing');
}
}
class Dances {
dance() {
console.log('Dancing');
}
}
class Acts {
act() {
console.log('Acting');
}
}
39
class Actor implements Acts {
act: () => void;
}
applyMixins(Actor, [Acts]);
class AllRounder implements Acts, Dances, Sings {
act: () => void;
dance: () => void;
sing: () => void;
}
applyMixins(AllRounder, [Acts, Dances, Sings]);
40
var actor = new Actor();
actor.act();
var allRounder = new AllRounder();
allRounder.act();
allRounder.dance();
allRounder.sing();
41
42
43
class Acts {
public message = 'Acting';
act() {
console.log(this.message);
}
}
class Actor implements Acts {
public message: string;
act: () => void;
}
applyMixins(Actor, [Acts]);
var actor = new Actor();
// Logs 'undefined', not 'Acting'
actor.act();
class Acts {
public static message = 'Acting';
act() {
alert(Acts.message);
}
}
45
https://github.com/DevStarSJ/Study/blob/master/Blog/Front-end/TypeScript/03.ObjectOrientationInTypeScript.md

More Related Content

What's hot

How Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerHow Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerAndrey Karpov
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency APISeok-joon Yun
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثةشرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثةجامعة القدس المفتوحة
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxyginecorehard_by
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعةجامعة القدس المفتوحة
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Asterisk: PVS-Studio Takes Up Telephony
Asterisk: PVS-Studio Takes Up TelephonyAsterisk: PVS-Studio Takes Up Telephony
Asterisk: PVS-Studio Takes Up TelephonyAndrey Karpov
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
 
Flashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacFlashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacESET Latinoamérica
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
Коварный code type ITGM #9
Коварный code type ITGM #9Коварный code type ITGM #9
Коварный code type ITGM #9Andrey Zakharevich
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортSergey Platonov
 
Javascript scoping
Javascript scopingJavascript scoping
Javascript scopingAditya Gaur
 
ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
ITGM #9 - Коварный CodeType, или от segfault'а к работающему кодуITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
ITGM #9 - Коварный CodeType, или от segfault'а к работающему кодуdelimitry
 

What's hot (20)

How Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerHow Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzer
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثةشرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxygine
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Asterisk: PVS-Studio Takes Up Telephony
Asterisk: PVS-Studio Takes Up TelephonyAsterisk: PVS-Studio Takes Up Telephony
Asterisk: PVS-Studio Takes Up Telephony
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
Flashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacFlashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas Mac
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Коварный code type ITGM #9
Коварный code type ITGM #9Коварный code type ITGM #9
Коварный code type ITGM #9
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репорт
 
Javascript scoping
Javascript scopingJavascript scoping
Javascript scoping
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
ITGM #9 - Коварный CodeType, или от segfault'а к работающему кодуITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
 

Similar to Pro typescript.ch03.Object Orientation in TypeScript

Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster DivingRonnBlack
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringCary Millsap
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDmitriy Sobko
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Ismar Silveira
 

Similar to Pro typescript.ch03.Object Orientation in TypeScript (20)

Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and Monitoring
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
srgoc
srgocsrgoc
srgoc
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 

More from Seok-joon Yun

Retrospective.2020 03
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03Seok-joon Yun
 
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image ConverterAWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image ConverterSeok-joon Yun
 
아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지Seok-joon Yun
 
Pro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, PerformancePro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, PerformanceSeok-joon Yun
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07Seok-joon Yun
 
Doing math with python.ch06
Doing math with python.ch06Doing math with python.ch06
Doing math with python.ch06Seok-joon Yun
 
Doing math with python.ch05
Doing math with python.ch05Doing math with python.ch05
Doing math with python.ch05Seok-joon Yun
 
Doing math with python.ch04
Doing math with python.ch04Doing math with python.ch04
Doing math with python.ch04Seok-joon Yun
 
Doing math with python.ch03
Doing math with python.ch03Doing math with python.ch03
Doing math with python.ch03Seok-joon Yun
 
Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02Seok-joon Yun
 
Doing math with python.ch01
Doing math with python.ch01Doing math with python.ch01
Doing math with python.ch01Seok-joon Yun
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsSeok-joon Yun
 
[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2Seok-joon Yun
 
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstatSeok-joon Yun
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4Seok-joon Yun
 
오렌지6.0 교육자료
오렌지6.0 교육자료오렌지6.0 교육자료
오렌지6.0 교육자료Seok-joon Yun
 
[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3
[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3
[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3Seok-joon Yun
 

More from Seok-joon Yun (20)

Retrospective.2020 03
Retrospective.2020 03Retrospective.2020 03
Retrospective.2020 03
 
Sprint & Jira
Sprint & JiraSprint & Jira
Sprint & Jira
 
Eks.introduce.v2
Eks.introduce.v2Eks.introduce.v2
Eks.introduce.v2
 
Eks.introduce
Eks.introduceEks.introduce
Eks.introduce
 
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image ConverterAWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
AWS DEV DAY SEOUL 2017 Buliding Serverless Web App - 직방 Image Converter
 
아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지아파트 시세,어쩌다 머신러닝까지
아파트 시세,어쩌다 머신러닝까지
 
Pro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, PerformancePro typescript.ch07.Exception, Memory, Performance
Pro typescript.ch07.Exception, Memory, Performance
 
Doing math with python.ch07
Doing math with python.ch07Doing math with python.ch07
Doing math with python.ch07
 
Doing math with python.ch06
Doing math with python.ch06Doing math with python.ch06
Doing math with python.ch06
 
Doing math with python.ch05
Doing math with python.ch05Doing math with python.ch05
Doing math with python.ch05
 
Doing math with python.ch04
Doing math with python.ch04Doing math with python.ch04
Doing math with python.ch04
 
Doing math with python.ch03
Doing math with python.ch03Doing math with python.ch03
Doing math with python.ch03
 
Doing mathwithpython.ch02
Doing mathwithpython.ch02Doing mathwithpython.ch02
Doing mathwithpython.ch02
 
Doing math with python.ch01
Doing math with python.ch01Doing math with python.ch01
Doing math with python.ch01
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threads
 
[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2[2015-07-20-윤석준] Oracle 성능 관리 2
[2015-07-20-윤석준] Oracle 성능 관리 2
 
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
 
오렌지6.0 교육자료
오렌지6.0 교육자료오렌지6.0 교육자료
오렌지6.0 교육자료
 
[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3
[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3
[2015-06-26] Oracle 성능 최적화 및 품질 고도화 3
 

Recently uploaded

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

Pro typescript.ch03.Object Orientation in TypeScript

  • 1.
  • 2. 2
  • 5. 5  Combination of recursion and late binding override 아니에요 ?  No, no, no. Recursion and late binding. 그래도 그냥 함수 override인데…
  • 6. 6 interface FileItem { path: string; contents: string[]; } class FileReader { getFiles(path: string, depth: number = 0) { var fileTree = []; var files = fs.readdirSync(path); for (var i = 0; i < files.length; i++) { var file = files[i]; var stats = fs.statSync(file); var fileItem; if (stats.isDirectory()) { // Add directory and contents fileItem = { path: file, contents: this.getFiles(file, (depth + 1)) }; } else { // Add file fileItem = { path: file, contents: [] }; } fileTree.push(fileItem); } return fileTree; } } class LimitedFileReader extends FileReader { constructor(public maxDepth: number) { super(); } getFiles(path: string, depth = 0) { if (depth > this.maxDepth) { return []; } return super.getFiles(path, depth); } } // instatiating an instance of LimitedFileReader var fileReader = new LimitedFileReader(1); // results in only the top level, and one additional level being read var files = fileReader.getFiles('path');
  • 7. 7  Private 제한자를 사용해 변수, 함수를 외부로부터 숨김  외부에 알리고 싶지 않은 것을 숨길 수 있음  외부에서 몰라도 되는 것을 숨기는 것은 추상화(Abstraction) 추상화나 캡슐화나… 내가 보기엔 다 거서 건데…
  • 8. 8 class Totalizer { private total = 0; private taxRateFactor = 0.2; addDonation(amount: number) { if (amount <= 0) { throw new Error('Donation exception'); } var taxRebate = amount * this.taxRateFactor; var totalDonation = amount + taxRebate; this.total += totalDonation; } getAmountRaised() { return this.total; } } var totalizer = new Totalizer(); totalizer.addDonation(100.00); var fundsRaised = totalizer.getAmountRaised(); // 120 console.log(fundsRaised);
  • 9. 9  Wrapper class로 원래 class를 감싸는 형태  상속관계 (is a)가 아닌 경우의 좋은 대안  코드 재사용성 측면에 있어서 가장 유용한 개념
  • 10. 10  Delegation : Has A  Ingeritance : Is A
  • 11. 11 interface ControlPanel { startAlarm(message: string): any; } interface Sensor { check(): any; } class MasterControlPanel { private sensors: Sensor[] = []; constructor() { // Instantiating the delegate HeatSensor this.sensors.push(new HeatSensor(this)); } start() { for (var i= 0; i < this.sensors.length; i++) { // Calling the delegate this.sensors[i].check(); } window.setTimeout(() => this.start(), 1000); } startAlarm(message: string) { console.log('Alarm! ' + message); } } class HeatSensor { private upperLimit = 38; private sensor = { read: function() { return Math.floor(Math.random() * 100); } }; constructor(private controlPanel: ControlPanel) { } check() { if (this.sensor.read() > this.upperLimit) { // Calling back to the wrapper this.controlPanel.startAlarm('Overheating!'); } } } var cp = new MasterControlPanel(); cp.start();
  • 12. 12  같은 함수 시그너쳐를 여러가지로 다르게 구현  Any structure with many similar structures
  • 13. 13 interface Vehicle { moveTo(x: number, y: number); } class Car implements Vehicle { moveTo(x: number, y: number) { console.log('Driving to ' + x + ' ' + y); } } class SportsCar extends Car { } class Airplane { moveTo(x: number, y: number) { console.log('Flying to ' + x + ' ' + y); } } function navigate(vehicle: Vehicle) { vehicle.moveTo(59.9436499, 10.7167959); } var airplane = new Airplane(); navigate(airplane); var car = new SportsCar(); navigate(car);
  • 14.
  • 15. 15
  • 16. 16 http://blog.cleancoder.com 단일 책임의 원칙 클래스는 오직 한가지 작업만 수행해야 하며, 한 가지 이유에 의해서만 변경되어야 함.
  • 17. 17 class Movie { private db: DataBase; constructor(private title: string, private year: number) { this.db = DataBase.connect('user:pw@mydb', ['movies']); } getTitle() { return this.title + ' (' + this.year + ')'; } save() { this.db.movies.save({ title: this.title, year: this.year }); } }
  • 18. 18 class Movie { constructor(private title: string, private year: number) { } getTitle() { return this.title + ' (' + this.year + ')'; } } class MovieRepository { private db: DataBase; constructor() { this.db = DataBase.connect('user:pw@mydb', ['movies']); } save(movie: Movie) { this.db.movies.save(JSON.stringify(movie)); } } // Movie var movie = new Movie('The Internship', 2013); // MovieRepository var movieRepository = new MovieRepository(); movieRepository.save(movie);
  • 19. 19 개방/폐쇄 원칙 확장에 대해서는 개방적이어여 하고, 수정에 대해서는 폐쇄적이어야 한다.
  • 20. 20 class RewardPointsCalculator { getPoints(transactionValue: number) { // 4 points per whole dollar spent return Math.floor(transactionValue) * 4; } } class DoublePointsCalculator extends RewardPointsCalculator { getPoints(transactionValue: number) { var standardPoints = super.getPoints(transactionValue); return standardPoints * 2; } } var pointsCalculator = new DoublePointsCalculator(); alert(pointsCalculator.getPoints(100.99));
  • 21. 21 리스코프 치환 원칙 S가 T의 하위속성이라면 프로그램의 변경없이 T의 객체를 S로 교체(치환)할 수 있어야 한다. Data Abstraction and Hireachy, 1998 - Babara Liskov
  • 22. 22 출처 : C#으로 배우는 적응형 코드
  • 23. 23 인터페이스 분리 원칙 인터페이스를 최대한 작게 만드는 것이 여러가지 기능을 하는 인터페이스 하나보다 더 좋다.
  • 24. 24 interface Printer { copyDocument(); printDocument(document: Document); stapleDocument(document: Document, tray: number); } interface Printer { printDocument(document: Document); } interface Stapler { stapleDocument(document: Document, tray: number); } interface Copier { copyDocument(); } class SimplePrinter implements Printer { printDocument(document: Document) { //... } } class SuperPrinter implements Printer, Stapler, Copier { printDocument(document: Document) { //... } copyDocument() { //... } stapleDocument(document: Document, tray: number) { //... } }
  • 25. 25 의존성 역주입 원칙 직접적인 의존을 피하고, 인터페이스에 의존하라.
  • 26. 26 class LightSwitch { private isOn = false; constructor(private light: Light) { } onPress() { if (this.isOn) { this.light.switchOff(); this.isOn = false; } else { this.light.switchOn(); this.isOn = true; } } } interface LightSource { switchOn(); switchOff(); } class Light { switchOn() { //... } switchOff() { //... } }
  • 27.
  • 28. 28
  • 31. 31 interface WheelCleaning { cleanWheels(): void; } class BasicWheelCleaning implements WheelCleaning { cleanWheels() { console.log('Soaping Wheel'); console.log('Brushing wheel'); } } class ExecutiveWheelCleaning extends BasicWheelCleaning { cleanWheels() { super.cleanWheels(); console.log('Waxing Wheel'); console.log('Rinsing Wheel'); } } interface BodyCleaning { cleanBody(): void; } class BasicBodyCleaning implements BodyCleaning { cleanBody() { console.log('Soaping car'); console.log('Rinsing Car'); } } class ExecutiveBodyCleaning extends BasicBodyCleaning { cleanBody() { super.cleanBody(); console.log('Waxing car'); console.log('Blow drying car'); } }
  • 32. 32 class CarWashProgram { constructor(private washLevel: number) { } runWash() { var wheelWash: WheelCleaning; var bodyWash: BodyCleaning; switch (this.washLevel) { case 1: wheelWash = new BasicWheelCleaning(); wheelWash.cleanWheels(); bodyWash = new BasicBodyCleaning(); bodyWash.cleanBody(); break; case 2: wheelWash = new BasicWheelCleaning(); wheelWash.cleanWheels(); bodyWash = new ExecutiveBodyCleaning(); bodyWash.cleanBody(); break; case 3: wheelWash = new ExecutiveWheelCleaning(); wheelWash.cleanWheels(); bodyWash = new ExecutiveBodyCleaning(); bodyWash.cleanBody(); break; } } }
  • 33. 33 interface ValetFactory { getWheelCleaning() : WheelCleaning; getBodyCleaning() : BodyCleaning; } class SilverWashFactory implements ValetFactory { getWheelCleaning() { return new BasicWheelCleaning(); } getBodyCleaning() { return new ExecutiveBodyCleaning(); } } class GoldWashFactory implements ValetFactory { getWheelCleaning() { return new ExecutiveWheelCleaning(); } getBodyCleaning() { return new ExecutiveBodyCleaning(); } } class BronzeWashFactory implements ValetFactory { getWheelCleaning() { return new BasicWheelCleaning(); } getBodyCleaning() { return new BasicBodyCleaning(); } }
  • 34. 34 class CarWashProgram { constructor(private cleaningFactory: ValetFactory) { } runWash() { var wheelWash = this.cleaningFactory.getWheelCleaning(); wheelWash.cleanWheels(); var bodyWash = this.cleaningFactory.getBodyCleaning(); bodyWash.cleanBody(); } }
  • 35.
  • 36. 36
  • 37. 37 function applyMixins(derivedCtor: any, baseCtors: any[]) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { if (name !== 'constructor') { derivedCtor.prototype[name] = baseCtor.prototype[name]; } }) }); }
  • 38. 38 class Sings { sing() { console.log('Singing'); } } class Dances { dance() { console.log('Dancing'); } } class Acts { act() { console.log('Acting'); } }
  • 39. 39 class Actor implements Acts { act: () => void; } applyMixins(Actor, [Acts]); class AllRounder implements Acts, Dances, Sings { act: () => void; dance: () => void; sing: () => void; } applyMixins(AllRounder, [Acts, Dances, Sings]);
  • 40. 40 var actor = new Actor(); actor.act(); var allRounder = new AllRounder(); allRounder.act(); allRounder.dance(); allRounder.sing();
  • 41. 41
  • 42. 42
  • 43. 43 class Acts { public message = 'Acting'; act() { console.log(this.message); } } class Actor implements Acts { public message: string; act: () => void; } applyMixins(Actor, [Acts]); var actor = new Actor(); // Logs 'undefined', not 'Acting' actor.act(); class Acts { public static message = 'Acting'; act() { alert(Acts.message); } }
  • 44.
  • 45. 45