SlideShare a Scribd company logo
객체지향의 올바른 이해와 전달
이세영 (effectiveprogramming.tistory.com)
객체지향의 올바른 이해와 전달
 현대 소프트웨어 기술의 핵심 개념이다
질문 : 클래스가 가지는 세가지 요소? 그 중에 가장 중요한 것은?
질문 : 어떤 코드가 객체지향적인 코드인가?
객체지향을 어떻게 설명하면 제대로 이해 시킬 수 있을까?
왜 이런 주제를 선정했는가?
1
객체지향 언어의 대두
 절차지향 언어(구조적 언어)
• 절차지향 언어의 시작은 1968년 에츠허르 데이크스트라(Dijkstra)의 ‘Go To Statement Considered Harmful’이라는 서신으로
봄.
• COBOL : 1959년
• C 언어 : 1972년
• Basic : 1964년
 객체지향 언어
• 1963년도 이반 서덜랜드의 논문 “Sketchpad, A Man-Machine Graphical Communication System”가 효시
• 시뮬라67 : 1967년
• 스몰토크 : 1970년대 시작, 1980년 대중에 공개.
• JAVA : 1995년
 절차지향 언어의 성공
• 빠르고 가볍고 직관적인 프로그래밍 언어
 현대의 소프트웨어
• Windows : C# / Android : Java / iOS : Objective-C / 웹 벡엔드 : Java / 웹 프론트엔드 : PHP, Javascript
• 사용률 기준 약 44% (2016년도 기준)를 객체지향 언어가 차지함.
• Matlab, Assembly 등의 특수 목적 언어들을 제외하면 대부분의 어플리케이션에 객체지향 언어가 사용됨.
성공적으로 사용되던 절차지향 언어 대신 객체지향 언어가 부각되고 있는 이유는?
관련도서
* 누가 소프트웨어의 심장을 만들었나
function1 function2 function3 function4
2
시대별 소프트웨어 적용 분야
 1930년대 후반 : 컴퓨터
• 암호 해독
 1940년대(소프트웨어 초창기) : 군사 분야
• 포탄 궤적용 표, 폭발 계산(원자폭탄 개발), 탄도 미사일 계산
 1950년대 : 과학 연구 분야(FORTRAN)
• 초신성 폭발, 수치해석, 일기예보
 1960년대 : 고등 제조 기술 및 비즈니스 분야(운영체제 및 COBOL 언어)
• 항공기 설계, 우주선 제작 및 궤도 계산, 비즈니스 소프트웨어
 1970년대 : PC 출현(유저인터페이스 + 네트워크 출현)
• SW 산업화 시대. 각종 산업에 소프트웨어가 두루 사용되기 시작. 애플I (1976)
 1980년대 : PC 시대
• MS-DOS(1981), 맥킨토시(1984) : 최초의 GUI와 마우스 채용
 1990년대 : WWW
• World Wide Web 출현, 웹 브라우저를 통한 정보 공유.(Mosaic 1993)
• 검색엔진 및 검색 포탈 출현(라이코스 1994, 알타비스타 1996, 야후 1995)
 2000년대 : 소셜 네트워크 및 집단 지성 시대
• Wikipidia(2001), 구글검색(2003), Facebook(2004), 아이폰(2007)
 2010년대 : 빅데이터 + 인공지능
• IBM 왓슨(2011년) ,이세돌 : 알파고 대결(2016)
소프트웨어가 발명된 이래로 그 적용 분야(도메인)는 지속적으로 확장되어 왔음.
관련도서
* 존 폰 노이만 그리고 현대 컴퓨팅의 기원
* 누가 소프트웨어의 심장을 만들었나
* 구글의 미래
3
소프트웨어가 가져야 할 가치
 소프트웨어 적용 분야의 확대
 요구사항의 종류와 양이 지속적으로 증가
 소프트웨어 유지 보수에 대한 요구 증가
• 60/60법칙 : 소프트웨어 비용의 60%는 유지보수이고, 그 중 60%는 기존 소프트웨어의 개선(기능 추가)이다.
 소프트웨어가 가져야 할 가치
소프트웨어는 늘어나는 요구사항들을 처리할 수 있어야 한다.
관련도서
* (우리가 미처 알지 못한) 소프트웨어 공학의 사실과 오해
* 켄트 벡의 구현 패턴
소통성
Communication
단순성
Simplicity
유연성
Flexibility
“협력”을 통한 확장
코드를 통한 커뮤니케이션 가능성기능을 구현하는 가장 단순한 방법 추구
다양한 요구사항을 쉽게 반영할 수 있는 소프트웨어의 구조적 특성
“소프트웨어가 존재하는 이유”
4
유연성이란?
 어린 왕자의 유연성 : 양이 든 상자
• “이건 상자다. 네가 가지고 싶어하는 양은 이 속에 있다...... 천만 뜻밖에도 어린 재판관의 얼굴이 환해졌다. 이게 바로 내가 갖
고 싶어하던 그림이야!”
 율리우스 카이사르의 유연성 : 추천 편지
• “카이사르는 선거구 ( )의 유권자 여러분이 던지는 표로써
후보자 ( )가 그들이 바라는 관직에 당선될 수 있기를 희망한다.”
 유연한 점괘
• “당신은 남들의 애정과 인정을 받아야만 하는 타입이면서도 스스로에 대해서는 엄격하네요.
겉으로는 절도 있고 자신을 잘 통제하는 것처럼 보이지만, 속으로는 걱정이 많고 불안감도 많이 느끼고요.
가끔은 내가 제대로 된 결정을 내렸을까 하고 심각하게 고민하는군요......”
 현실 세계에서의 유연성 : 청첩장
• 동일한 내용과 외형의 청첩장을 미리 만들어 놓고, 실제 전달할 때 받을 사람 이름만 적어서 준다.
다양한 요구사항을 쉽게 반영할 수 있는 소프트웨어의 구조적 특성
관련도서
* 로마인 이야기 제6권
* Meme (수잔 서덜랜드)
* 어린왕자
5
유연성 확보 전략
 오케스트라의 비유
다루고자 하는 대상들의 차이점을 감추고 공통 부분만으로 대상을 다룬다.
지휘자
바순
트롬본트럼펫
튜바하프
지휘자
바이올린1 첼로
피아노
플루트 호른
콘트라베비올라바이올린2
바이올린1 연주하세요
피아노 연주하세요
하프 연주하세요
플루트 연주하세요
바이올린2 연주하세요
트럼펫 연주하세요
바순 연주하세요
바이올린1 멈추세요
피아노 멈추세요
하프 멈추세요
플루트 멈추세요
바이올린2 멈추세요
트럼펫 멈추세요
바순 멈추세요
연주자 여러분,
연주하세요
연주자 여러분,
멈추세요
연주자
바순
트롬본트럼펫
튜바하프
바이올린1 첼로
피아노
플루트 호른
콘트라베비올라바이올린2
대금
6
객체지향(Object Oriented Programming)
 객체지향 4대 특성
 객체지향의 유연성 전략
객체들간의 협력과 책임, 역할을 중심으로 문제를 해결하는 프로그래밍 언어
공통점을 추출한다.
(차이점을 감춘다.) 차이점을 더한다. 공통점을 통해 대상을 다룬다.“대상화” 한다.
공통점
연주자 연주자
하프
연주자
연주자
플루트
연주자
피아노
연주자
지휘자
추상화
(Abstraction)
상속
(Inheritance)
다형성
(Polymorphism)
캡슐화
(Encapsulation)
정보 은닉
(Information Hiding)
피아노
연주자
플루트
연주자
하프
연주자
하프
연주자
플루트
연주자
피아노
연주자
관련도서
* 객체지향의 사실과 오해
“연주하세요”
“멈추세요”
7
추상화(Abstraction)
 추상화(Abstraction)
• 대상들의 공통점을 추출해 냄.
• 해결하고자 하는 문제와 무관한 사항을 제거.
대상들의 공통점을 추출해 내고, 해결하고자 하는 문제와 무관한 항목을 제거하는 과정.
비올라 연주자
트럼펫 연주자
피아노 연주자
악기
악보
복장
헤어스타일
성별
......
연주한다
멈춘다
걷는다
먹는다
잔다
......
플루트 연주자
하프 연주자
악기
연주한다
멈춘다
공통점을 추출한다.
(차이점을 감춘다.)
불필요한 사항을 제거한다
관련도서
* 객체지향의 사실과 오해
8
캡슐화(Encapsulation)
 클래스(Class) = 타입 + 속성 + 행위
 객체
• 클래스 = 설계, 객체 = 실제
 비 객체지향에서의 타입(Type)
• 데이터의 자료형(char, short, int, long 등)
 객체가 가진 것 중에서 가장 중요한 것은 타입(Type)이다
• 객체를 다루는 방법을 결정하는 단위
• 객체의 구현 및 다른 객체와의 협력 관계를 결정하는 요소
요구사항을 행위와 속성을 묶고, 이를 실제로 다룰 수 있는 대상으로 만든다.
연주자 Musician
악기 Instrument instrument;
연주한다 void play();
멈춘다 void stop();
1. 타입(Type) : 객체를 지칭하는 특성
2. 속성(Attribute) : 데이터 및 참조를 저장
3. 행위(Operation) : 제어 및 연산
꽃 (이상화)
내가 그의 이름을 불러주기 전에는
그는 다만
하나의 몸짓에 지나지 않았다.
내가 그의 이름을 불러주었을 때
그는 나에게로 와서
꽃이 되었다.
......
우리들은 모두
무엇이 되고 싶다.
나는 너에게 너는 나에게
잊혀지지 않는 하나의 의미가 되고 싶다.
9
Musician m = ..X.. ;
m.play();
상속(Inheritance)
 상속의 나쁜 정의
• 한 클래스가 기반 클래스에 정의된 속성과 행위를 받아서 사용하는 것.
• 중복 코드를 줄일 수 있다. (재사용?)
 상속의 올바른 정의 : is – a 관계
• 기반 클래스의 타입과 행위, 속성을 물려 받는 것.
• is – a 관계의 의미 : 파생 클래스가 기반 클래스로 불려질 수 있다.
• 객체가 기반 타입으로 다뤄 질 수 있도록 만들기 위한 특성.
 상속 받는 것 중에 가장 중요한 것은 타입(Type)이다
상속은 상위 클래스의 타입을 하위 클래스들에게 부여한다.
하프
연주자
연주자
플루트
연주자
피아노
연주자
플루트 연주자를 “연주자” 라고 부를 수 있는 이유는?
하프
연주자
플루트
연주자
피아노
연주자
연주자 연주자 연주자
플루트 연주자는 동시에 연주자이기 때문이다.
상속을 통해 속성과 행위와 타입을 상속 받는다.
10
기반 클래스
파생 클래스
다형성(Polymorphism)
 다형성(Polymorphism)의 정의
• from the Greek meaning “= having multiple forms”
• 하나의 객체가 서로 다른 여러 타입으로 지칭될 수 있음을 일컫는 말.
• 형(形) = 타입을 의미한다.
 다형성의 효과
• 다양한 하위 타입 객체를 상위 타입 한 개로 취급한다.
• 하위 타입 객체가 추가 / 변경 / 삭제 되더라도 상위 타입을 쓰는 코드는 변경되지 않는다.
하위 클래스를 직접 다루지 않고 상위 타입으로 다룬다
연주자
플루트
연주자
연주자
FluteMusician fm = new FluteMusician();
fm.playFlute();
ViolinMusician vm = new ViolinMusician();
vm.playViolin();
Musician m = new FluteMusician();
m.play();
개별 연주자의 변경으로부터 자유롭다
개별 연주자의 추가/ API변경/ 삭제에
영향을 받는다.
11
Musician
FluteMusician
객체지향 삼각형
객체지향의 모든 특성을 한 눈에 이해할 수 있는 구조.
1. 추상화(Abstraction)
2. 캡슐화(Encapsulation = 대상화)
3. 상속(Inheritance)
4. 다형성(Polymorphism)
추가 삭제
유연성(Flexibility)
변경
12
의존(Dependency)과 유연성
 의존(Dependency)
• 한 클래스에 다른 클래스의 요소(클래스명, 메소드 호출 등)가 등장함.
• A 클래스 구현에 B 클래스의 요소(타입명, 메소드 호출, 필드 접근)가 등장하면 A가 B에 의존한다고 말한다.
1. A가 B에 의존한다 = “B가 A의 코드에 나온다”
2. = B의 수정/변경 시 A도 수정/변경 된다
3. = B는 자유롭게 수정될 수 없다
4. = 유연하지 않은 코드
의존한다 = “코드에 나온다”
관련도서 : 자바 API 디자인
class FluteMusician{
public void play(){}
}
class Maestro{
FluteMusician fm = new FluteMusician(); // 1
HarpMusician hm = new HarpMusician();
PianoMusician pm = new PianoMusician();
public void play(){
fm.play(); // 2
hm.play();
pm.play();
}
}
Maestro FluteMusician
1. create
2. play
HarpMusician
PianoMusician
13
의존(Dependency)과 유연성
의존의 문제 = 수정의 목적과 수정의 대상 간에 불일치
가장 좋은 의존 = 의존하지 않는 것
하지만 “어떤 객체도 섬이 아니다” (켄트 벡)
좋은 의존 = 의존이 최소화 되는 것 / (거의) 변하지 않을 것에 의존하는 것
변하지 않을 것에 의존해야 유연성이 생긴다.
class FluteMusician{
/* 1. 속성(attributes) */
public void play(){
/* 2. 구현(implementations) */
}
/* 3. 특수 메소드 */
}
class HarpMusician{
/* 1. 속성(attributes) */
public void play(){
/* 2. 구현(implementations) */
}
/* 3. 특수 메소드 */
}
interface Musician{
public void play();
}
1. 속성(= 변수)이 없다. = 속성이 수정되지 않는다.
2. 구현부가 없다. = 구현이 수정되지 않는다.
3. 특수 메소드가 없다. = 대체 가능하다.
14
공통점
좋은 의존
모든 클래스들은 오직 Musician이라는 타입에만 의존한다.
= Musician이외의 어떤 객체가 수정 돼도 다른 객체에 영향을 주지 않는다.
class Maestro{
private List<Musician> musicians = new ArrayList<Musician>();
public void add(Musician m){ musicians.add(m); }
public void play(){
for(Musician each : musicians) each.play();
}
public void stop(){
for(Musician each : musicians) each.stop();
}
}
속성도 구현부도 없기 때문에
수정될 가능성도 적다
class PianoMusician implements Musician {
public void play(){/* ... */}
public void stop(){/* ... */}
}
class HarpMusician implements Musician {
public void play(){/* ... */}
public void stop(){/* ... */}
}
class FluteMusician implements Musician {
public void play(){/* ... */}
public void stop(){/* ... */}
}
interface Musician{
public void play();
public void stop();
}
나쁜 의존
15
정보 은닉(Information Hiding)
 정보 은닉의 목적 = 의존의 최소화
 정보 은닉의 역할
• 의존해야 할 것과 의존하지 말아야 할 것을 분리한다.
• 의도하지 않은 의존이 발생하지 않도록 차단한다.
1. 객체의 구체적인 타입 은닉 = 다형성(Polymorphism)
• 상위 타입 캐스팅을 통해 객체의 구체적인 타입을 감춤.
2. 객체의 필드 및 메소드 은닉 = 캡슐화(Encapsulation)
• 외부 객체와의 협력에 불필요한 필드와 메소드들을 감춘다.
• 객체간의 의존성을 떨어 뜨린다.
3. 객체의 구현 은닉 = Interface, Abstract Class
• 인터페이스 혹은 추상 클래스만 제공하고 구체 클래스를 감춤.
• 구체 클래스의 존재 유무, 구현 정도, 교체 여부와 상관 없이 개발을 진행할 수 있음.
모든 객체지향 언어의 요소를 활용하여 객체에 대한 구체적인 정보를 노출시키지 않도
록 하는 기법
참고 블로그
* http://egloos.zum.com/aeternum/v/1232020
16
정보 은닉을 통한 의존성 최소화
 인터페이스 = 추상적인 것
• 구현부가 없지만 구현들을 대표할 수 있는 추상적인 요소.
 추상적인 것에 의존 = 변경의 이유가 가장 적은 것에 의존
오직 “Type” 하나에만 의존하도록 만든다
“Type”
Type +
의존(Dependency)
의존(Dependency)
class Client{
private Iface is;
public void setIface(Iface is){
this.is = is;
}
}
interface Iface{}
class Impl1 implements Iface{}
class Impl2 implements Iface{}
class Impl3 implements Iface{}
구현 은닉 =
구체적 타입 은닉 =
필드 / 메소드 은닉
17
소프트웨어 기술
effectiveprogramming.tistory.com
언어 객체지향
디자인 패턴
UML
구현 패턴
네트워크
동시성 리팩토링
Unit Test
아키텍쳐
패턴
Agile
Scrum
DevOps
구현 영역
설계 영역
프로세스 영역
18
객체지향의 활용
상태를 객체화하여 상태 변수를 제거한다.
class Window{
boolean isBoardered = false; // 상태 변수
public void setBoarder(boolean isBoardered){ this.isBoardered = isBoardered; }
public void draw(){
// 상태 변수에 의한 조건문 발생
if(isBoardered) System.out.println("boardered Window");
else System.out.println("unboardered Window");
}
}
class Window{
IWindow window;
public void setBoarder(boolean isBoardered){
if(isBoardered) window = new BoarderedWindow();
else window = new UnboarderedWindow();
}
public void draw() { window.draw(); }
}
interface IWindow{
public void draw();
}
class BoarderedWindow implements IWindow{
@Override public void draw() { System.out.println("boardered Window"); }
}
class UnboarderedWindow implements IWindow{
@Override public void draw() { System.out.println("unboardered Window"); }
}
19
객체지향의 활용
Enum의 객체지향 특성을 활용하여 반복되는 코드를 제거한다.
class Boundary{
int northLimit = 100;
int southLimit = 50;
int eastLimit = 20;
int westLimit = 10;
// getters
public int getNorthLimit() {
return northLimit; }
public int getSouthLimit() {
return southLimit; }
public int getEastLimit() {
return eastLimit; }
public int getWestLimit() {
return westLimit; }
// setters
public void setNorthLimit(int northLimit){
this.northLimit = northLimit; }
public void setSouthLimit(int southLimit){
this.southLimit = southLimit; }
public void setEastLimit(int eastLimit){
this.eastLimit = eastLimit; }
public void setWestLimit(int westLimit){
this.westLimit = westLimit; }
}
class Boundary{
int[] boundaries =
new int[Direction.values().length];
public int getLimit(Direction direction) {
return boundaries[direction.ordinal()];
}
public void setLimit(
Direction direction, int limit) {
boundaries[direction.ordinal()] = limit;
}
}
enum Direction{
NORTH,
SOUTH,
EAST,
WEST
;
}
20
객체지향의 활용
불필요한 조건문이 발생하지 않도록 억제한다.
class LineDrawer{
public void draw(){ System.out.println("line draw"); }
}
class Background{
LineDrawer lineDrawer = null;
public void addLine(LineDrawer lineDrawer){ this.lineDrawer = lineDrawer; }
public void draw(){ System.out.println("background draw"); }
}
class Use{
LineDrawer lineDrawer = null;
Background background = null;
public void setLineDrawer(LineDrawer lineDrawer) { this.lineDrawer = lineDrawer; }
public void setBackground(Background background) {
this.background = background;
}
public void draw(){
if(background != null) background.draw();
if(lineDrawer != null) lineDrawer.draw();
}
}
21
객체지향의 활용
Special Case Pattern
class LineDrawer{
public void draw(){ System.out.println("line draw"); }
}
class NullLineDrawer extends LineDrawer{
@Override public void draw(){}
}
class Background{
LineDrawer lineDrawer = null;
public void addLine(LineDrawer lineDrawer){ this.lineDrawer = lineDrawer; }
public void draw(){ System.out.println("background draw"); }
}
class NullBackground extends Background{
@Override public void draw(){}
}
class Use{
LineDrawer lineDrawer = new NullLineDrawer(); // Null을 대신하여 사용된 Null 객체
Background background = new NullBackground();
/* ……… */
public void draw(){
background.draw();
lineDrawer.draw();
}
}
22
객체지향의 활용
enum에 의한 switch-case 문의 발생을 방지한다.
enum PriceCode{
CHILDREN
,NORMAL
,NEW_RELEASE
;
}
class Use{
PriceCode priceCode = PriceCode.CHILDREN;
public int getPrice(){
int price = 0;
switch(priceCode){
case CHILDREN:
price = 1000;
break;
case NORMAL :
price = 1500;
break;
case NEW_RELEASE :
price = 2000;
break;
default:
price = 0;
break;
}
return price;
}
}
enum PriceCode{
CHILDREN{
public int getPrice(){
return 1000;
}
}
,NORMAL{
public int getPrice(){
return 1500;
}
}
,NEW_RELEASE{
public int getPrice(){
return 2000;
}
}
;
abstract public int getPrice();
}
class Use{
PriceCode priceCode = PriceCode.CHILDREN;
public int getPrice(){
return priceCode.getPrice();
}
}
23
객체지향의 활용
용도는 한가지인데 이용하는 변수가 여럿인 경우
class Table{
private int index;
private int value;
private int condition;
public static final int BY_INDEX = 1;
public static final int BY_VALUE = 2;
public static final int BY_CONDITION = 3;
private int coloringType;
public void draw(){
if(coloringType == BY_INDEX){
Color color = byIndex(index);
}
else if(coloringType == BY_VALUE){
Color color = byValue(value);
}
else if(coloringType == BY_CONDITION){
Color color = byCondition(value);
}
}
public Color byIndex(int index){ return null;}
public Color byValue(int value){ return null;}
public Color byCondition(int condition){ return null;}
}
24
객체지향의 활용
“this” 참조를 넘겨 필요한 정보를 스스로 꺼내가도록 함.
class Table{
private int index;
private int value;
private int condition;
public int getIndex() { return index; }
public int getValue() { return value; }
public int getCondition() { return condition; }
private Coloring coloring;
public void draw(){
Color color = coloring.getColor(this);
}
}
interface Coloring{
public Color getColor(Table table);
}
class ByIndex implements Coloring{
public Color getColor(Table table){
int index = table.getIndex();
return null;
}
}
class ByValue implements Coloring{
public Color getColor(Table table){
int value = table.getValue();
return null;
}
}
class ByCondition implements Coloring{
public Color getColor(Table table){
int condition = table.getCondition();
return null;
}
}
25

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

객체지향의 올바른 이해와 전달

  • 1. 객체지향의 올바른 이해와 전달 이세영 (effectiveprogramming.tistory.com)
  • 2. 객체지향의 올바른 이해와 전달  현대 소프트웨어 기술의 핵심 개념이다 질문 : 클래스가 가지는 세가지 요소? 그 중에 가장 중요한 것은? 질문 : 어떤 코드가 객체지향적인 코드인가? 객체지향을 어떻게 설명하면 제대로 이해 시킬 수 있을까? 왜 이런 주제를 선정했는가? 1
  • 3. 객체지향 언어의 대두  절차지향 언어(구조적 언어) • 절차지향 언어의 시작은 1968년 에츠허르 데이크스트라(Dijkstra)의 ‘Go To Statement Considered Harmful’이라는 서신으로 봄. • COBOL : 1959년 • C 언어 : 1972년 • Basic : 1964년  객체지향 언어 • 1963년도 이반 서덜랜드의 논문 “Sketchpad, A Man-Machine Graphical Communication System”가 효시 • 시뮬라67 : 1967년 • 스몰토크 : 1970년대 시작, 1980년 대중에 공개. • JAVA : 1995년  절차지향 언어의 성공 • 빠르고 가볍고 직관적인 프로그래밍 언어  현대의 소프트웨어 • Windows : C# / Android : Java / iOS : Objective-C / 웹 벡엔드 : Java / 웹 프론트엔드 : PHP, Javascript • 사용률 기준 약 44% (2016년도 기준)를 객체지향 언어가 차지함. • Matlab, Assembly 등의 특수 목적 언어들을 제외하면 대부분의 어플리케이션에 객체지향 언어가 사용됨. 성공적으로 사용되던 절차지향 언어 대신 객체지향 언어가 부각되고 있는 이유는? 관련도서 * 누가 소프트웨어의 심장을 만들었나 function1 function2 function3 function4 2
  • 4. 시대별 소프트웨어 적용 분야  1930년대 후반 : 컴퓨터 • 암호 해독  1940년대(소프트웨어 초창기) : 군사 분야 • 포탄 궤적용 표, 폭발 계산(원자폭탄 개발), 탄도 미사일 계산  1950년대 : 과학 연구 분야(FORTRAN) • 초신성 폭발, 수치해석, 일기예보  1960년대 : 고등 제조 기술 및 비즈니스 분야(운영체제 및 COBOL 언어) • 항공기 설계, 우주선 제작 및 궤도 계산, 비즈니스 소프트웨어  1970년대 : PC 출현(유저인터페이스 + 네트워크 출현) • SW 산업화 시대. 각종 산업에 소프트웨어가 두루 사용되기 시작. 애플I (1976)  1980년대 : PC 시대 • MS-DOS(1981), 맥킨토시(1984) : 최초의 GUI와 마우스 채용  1990년대 : WWW • World Wide Web 출현, 웹 브라우저를 통한 정보 공유.(Mosaic 1993) • 검색엔진 및 검색 포탈 출현(라이코스 1994, 알타비스타 1996, 야후 1995)  2000년대 : 소셜 네트워크 및 집단 지성 시대 • Wikipidia(2001), 구글검색(2003), Facebook(2004), 아이폰(2007)  2010년대 : 빅데이터 + 인공지능 • IBM 왓슨(2011년) ,이세돌 : 알파고 대결(2016) 소프트웨어가 발명된 이래로 그 적용 분야(도메인)는 지속적으로 확장되어 왔음. 관련도서 * 존 폰 노이만 그리고 현대 컴퓨팅의 기원 * 누가 소프트웨어의 심장을 만들었나 * 구글의 미래 3
  • 5. 소프트웨어가 가져야 할 가치  소프트웨어 적용 분야의 확대  요구사항의 종류와 양이 지속적으로 증가  소프트웨어 유지 보수에 대한 요구 증가 • 60/60법칙 : 소프트웨어 비용의 60%는 유지보수이고, 그 중 60%는 기존 소프트웨어의 개선(기능 추가)이다.  소프트웨어가 가져야 할 가치 소프트웨어는 늘어나는 요구사항들을 처리할 수 있어야 한다. 관련도서 * (우리가 미처 알지 못한) 소프트웨어 공학의 사실과 오해 * 켄트 벡의 구현 패턴 소통성 Communication 단순성 Simplicity 유연성 Flexibility “협력”을 통한 확장 코드를 통한 커뮤니케이션 가능성기능을 구현하는 가장 단순한 방법 추구 다양한 요구사항을 쉽게 반영할 수 있는 소프트웨어의 구조적 특성 “소프트웨어가 존재하는 이유” 4
  • 6. 유연성이란?  어린 왕자의 유연성 : 양이 든 상자 • “이건 상자다. 네가 가지고 싶어하는 양은 이 속에 있다...... 천만 뜻밖에도 어린 재판관의 얼굴이 환해졌다. 이게 바로 내가 갖 고 싶어하던 그림이야!”  율리우스 카이사르의 유연성 : 추천 편지 • “카이사르는 선거구 ( )의 유권자 여러분이 던지는 표로써 후보자 ( )가 그들이 바라는 관직에 당선될 수 있기를 희망한다.”  유연한 점괘 • “당신은 남들의 애정과 인정을 받아야만 하는 타입이면서도 스스로에 대해서는 엄격하네요. 겉으로는 절도 있고 자신을 잘 통제하는 것처럼 보이지만, 속으로는 걱정이 많고 불안감도 많이 느끼고요. 가끔은 내가 제대로 된 결정을 내렸을까 하고 심각하게 고민하는군요......”  현실 세계에서의 유연성 : 청첩장 • 동일한 내용과 외형의 청첩장을 미리 만들어 놓고, 실제 전달할 때 받을 사람 이름만 적어서 준다. 다양한 요구사항을 쉽게 반영할 수 있는 소프트웨어의 구조적 특성 관련도서 * 로마인 이야기 제6권 * Meme (수잔 서덜랜드) * 어린왕자 5
  • 7. 유연성 확보 전략  오케스트라의 비유 다루고자 하는 대상들의 차이점을 감추고 공통 부분만으로 대상을 다룬다. 지휘자 바순 트롬본트럼펫 튜바하프 지휘자 바이올린1 첼로 피아노 플루트 호른 콘트라베비올라바이올린2 바이올린1 연주하세요 피아노 연주하세요 하프 연주하세요 플루트 연주하세요 바이올린2 연주하세요 트럼펫 연주하세요 바순 연주하세요 바이올린1 멈추세요 피아노 멈추세요 하프 멈추세요 플루트 멈추세요 바이올린2 멈추세요 트럼펫 멈추세요 바순 멈추세요 연주자 여러분, 연주하세요 연주자 여러분, 멈추세요 연주자 바순 트롬본트럼펫 튜바하프 바이올린1 첼로 피아노 플루트 호른 콘트라베비올라바이올린2 대금 6
  • 8. 객체지향(Object Oriented Programming)  객체지향 4대 특성  객체지향의 유연성 전략 객체들간의 협력과 책임, 역할을 중심으로 문제를 해결하는 프로그래밍 언어 공통점을 추출한다. (차이점을 감춘다.) 차이점을 더한다. 공통점을 통해 대상을 다룬다.“대상화” 한다. 공통점 연주자 연주자 하프 연주자 연주자 플루트 연주자 피아노 연주자 지휘자 추상화 (Abstraction) 상속 (Inheritance) 다형성 (Polymorphism) 캡슐화 (Encapsulation) 정보 은닉 (Information Hiding) 피아노 연주자 플루트 연주자 하프 연주자 하프 연주자 플루트 연주자 피아노 연주자 관련도서 * 객체지향의 사실과 오해 “연주하세요” “멈추세요” 7
  • 9. 추상화(Abstraction)  추상화(Abstraction) • 대상들의 공통점을 추출해 냄. • 해결하고자 하는 문제와 무관한 사항을 제거. 대상들의 공통점을 추출해 내고, 해결하고자 하는 문제와 무관한 항목을 제거하는 과정. 비올라 연주자 트럼펫 연주자 피아노 연주자 악기 악보 복장 헤어스타일 성별 ...... 연주한다 멈춘다 걷는다 먹는다 잔다 ...... 플루트 연주자 하프 연주자 악기 연주한다 멈춘다 공통점을 추출한다. (차이점을 감춘다.) 불필요한 사항을 제거한다 관련도서 * 객체지향의 사실과 오해 8
  • 10. 캡슐화(Encapsulation)  클래스(Class) = 타입 + 속성 + 행위  객체 • 클래스 = 설계, 객체 = 실제  비 객체지향에서의 타입(Type) • 데이터의 자료형(char, short, int, long 등)  객체가 가진 것 중에서 가장 중요한 것은 타입(Type)이다 • 객체를 다루는 방법을 결정하는 단위 • 객체의 구현 및 다른 객체와의 협력 관계를 결정하는 요소 요구사항을 행위와 속성을 묶고, 이를 실제로 다룰 수 있는 대상으로 만든다. 연주자 Musician 악기 Instrument instrument; 연주한다 void play(); 멈춘다 void stop(); 1. 타입(Type) : 객체를 지칭하는 특성 2. 속성(Attribute) : 데이터 및 참조를 저장 3. 행위(Operation) : 제어 및 연산 꽃 (이상화) 내가 그의 이름을 불러주기 전에는 그는 다만 하나의 몸짓에 지나지 않았다. 내가 그의 이름을 불러주었을 때 그는 나에게로 와서 꽃이 되었다. ...... 우리들은 모두 무엇이 되고 싶다. 나는 너에게 너는 나에게 잊혀지지 않는 하나의 의미가 되고 싶다. 9 Musician m = ..X.. ; m.play();
  • 11. 상속(Inheritance)  상속의 나쁜 정의 • 한 클래스가 기반 클래스에 정의된 속성과 행위를 받아서 사용하는 것. • 중복 코드를 줄일 수 있다. (재사용?)  상속의 올바른 정의 : is – a 관계 • 기반 클래스의 타입과 행위, 속성을 물려 받는 것. • is – a 관계의 의미 : 파생 클래스가 기반 클래스로 불려질 수 있다. • 객체가 기반 타입으로 다뤄 질 수 있도록 만들기 위한 특성.  상속 받는 것 중에 가장 중요한 것은 타입(Type)이다 상속은 상위 클래스의 타입을 하위 클래스들에게 부여한다. 하프 연주자 연주자 플루트 연주자 피아노 연주자 플루트 연주자를 “연주자” 라고 부를 수 있는 이유는? 하프 연주자 플루트 연주자 피아노 연주자 연주자 연주자 연주자 플루트 연주자는 동시에 연주자이기 때문이다. 상속을 통해 속성과 행위와 타입을 상속 받는다. 10 기반 클래스 파생 클래스
  • 12. 다형성(Polymorphism)  다형성(Polymorphism)의 정의 • from the Greek meaning “= having multiple forms” • 하나의 객체가 서로 다른 여러 타입으로 지칭될 수 있음을 일컫는 말. • 형(形) = 타입을 의미한다.  다형성의 효과 • 다양한 하위 타입 객체를 상위 타입 한 개로 취급한다. • 하위 타입 객체가 추가 / 변경 / 삭제 되더라도 상위 타입을 쓰는 코드는 변경되지 않는다. 하위 클래스를 직접 다루지 않고 상위 타입으로 다룬다 연주자 플루트 연주자 연주자 FluteMusician fm = new FluteMusician(); fm.playFlute(); ViolinMusician vm = new ViolinMusician(); vm.playViolin(); Musician m = new FluteMusician(); m.play(); 개별 연주자의 변경으로부터 자유롭다 개별 연주자의 추가/ API변경/ 삭제에 영향을 받는다. 11 Musician FluteMusician
  • 13. 객체지향 삼각형 객체지향의 모든 특성을 한 눈에 이해할 수 있는 구조. 1. 추상화(Abstraction) 2. 캡슐화(Encapsulation = 대상화) 3. 상속(Inheritance) 4. 다형성(Polymorphism) 추가 삭제 유연성(Flexibility) 변경 12
  • 14. 의존(Dependency)과 유연성  의존(Dependency) • 한 클래스에 다른 클래스의 요소(클래스명, 메소드 호출 등)가 등장함. • A 클래스 구현에 B 클래스의 요소(타입명, 메소드 호출, 필드 접근)가 등장하면 A가 B에 의존한다고 말한다. 1. A가 B에 의존한다 = “B가 A의 코드에 나온다” 2. = B의 수정/변경 시 A도 수정/변경 된다 3. = B는 자유롭게 수정될 수 없다 4. = 유연하지 않은 코드 의존한다 = “코드에 나온다” 관련도서 : 자바 API 디자인 class FluteMusician{ public void play(){} } class Maestro{ FluteMusician fm = new FluteMusician(); // 1 HarpMusician hm = new HarpMusician(); PianoMusician pm = new PianoMusician(); public void play(){ fm.play(); // 2 hm.play(); pm.play(); } } Maestro FluteMusician 1. create 2. play HarpMusician PianoMusician 13
  • 15. 의존(Dependency)과 유연성 의존의 문제 = 수정의 목적과 수정의 대상 간에 불일치 가장 좋은 의존 = 의존하지 않는 것 하지만 “어떤 객체도 섬이 아니다” (켄트 벡) 좋은 의존 = 의존이 최소화 되는 것 / (거의) 변하지 않을 것에 의존하는 것 변하지 않을 것에 의존해야 유연성이 생긴다. class FluteMusician{ /* 1. 속성(attributes) */ public void play(){ /* 2. 구현(implementations) */ } /* 3. 특수 메소드 */ } class HarpMusician{ /* 1. 속성(attributes) */ public void play(){ /* 2. 구현(implementations) */ } /* 3. 특수 메소드 */ } interface Musician{ public void play(); } 1. 속성(= 변수)이 없다. = 속성이 수정되지 않는다. 2. 구현부가 없다. = 구현이 수정되지 않는다. 3. 특수 메소드가 없다. = 대체 가능하다. 14 공통점
  • 16. 좋은 의존 모든 클래스들은 오직 Musician이라는 타입에만 의존한다. = Musician이외의 어떤 객체가 수정 돼도 다른 객체에 영향을 주지 않는다. class Maestro{ private List<Musician> musicians = new ArrayList<Musician>(); public void add(Musician m){ musicians.add(m); } public void play(){ for(Musician each : musicians) each.play(); } public void stop(){ for(Musician each : musicians) each.stop(); } } 속성도 구현부도 없기 때문에 수정될 가능성도 적다 class PianoMusician implements Musician { public void play(){/* ... */} public void stop(){/* ... */} } class HarpMusician implements Musician { public void play(){/* ... */} public void stop(){/* ... */} } class FluteMusician implements Musician { public void play(){/* ... */} public void stop(){/* ... */} } interface Musician{ public void play(); public void stop(); } 나쁜 의존 15
  • 17. 정보 은닉(Information Hiding)  정보 은닉의 목적 = 의존의 최소화  정보 은닉의 역할 • 의존해야 할 것과 의존하지 말아야 할 것을 분리한다. • 의도하지 않은 의존이 발생하지 않도록 차단한다. 1. 객체의 구체적인 타입 은닉 = 다형성(Polymorphism) • 상위 타입 캐스팅을 통해 객체의 구체적인 타입을 감춤. 2. 객체의 필드 및 메소드 은닉 = 캡슐화(Encapsulation) • 외부 객체와의 협력에 불필요한 필드와 메소드들을 감춘다. • 객체간의 의존성을 떨어 뜨린다. 3. 객체의 구현 은닉 = Interface, Abstract Class • 인터페이스 혹은 추상 클래스만 제공하고 구체 클래스를 감춤. • 구체 클래스의 존재 유무, 구현 정도, 교체 여부와 상관 없이 개발을 진행할 수 있음. 모든 객체지향 언어의 요소를 활용하여 객체에 대한 구체적인 정보를 노출시키지 않도 록 하는 기법 참고 블로그 * http://egloos.zum.com/aeternum/v/1232020 16
  • 18. 정보 은닉을 통한 의존성 최소화  인터페이스 = 추상적인 것 • 구현부가 없지만 구현들을 대표할 수 있는 추상적인 요소.  추상적인 것에 의존 = 변경의 이유가 가장 적은 것에 의존 오직 “Type” 하나에만 의존하도록 만든다 “Type” Type + 의존(Dependency) 의존(Dependency) class Client{ private Iface is; public void setIface(Iface is){ this.is = is; } } interface Iface{} class Impl1 implements Iface{} class Impl2 implements Iface{} class Impl3 implements Iface{} 구현 은닉 = 구체적 타입 은닉 = 필드 / 메소드 은닉 17
  • 19. 소프트웨어 기술 effectiveprogramming.tistory.com 언어 객체지향 디자인 패턴 UML 구현 패턴 네트워크 동시성 리팩토링 Unit Test 아키텍쳐 패턴 Agile Scrum DevOps 구현 영역 설계 영역 프로세스 영역 18
  • 20. 객체지향의 활용 상태를 객체화하여 상태 변수를 제거한다. class Window{ boolean isBoardered = false; // 상태 변수 public void setBoarder(boolean isBoardered){ this.isBoardered = isBoardered; } public void draw(){ // 상태 변수에 의한 조건문 발생 if(isBoardered) System.out.println("boardered Window"); else System.out.println("unboardered Window"); } } class Window{ IWindow window; public void setBoarder(boolean isBoardered){ if(isBoardered) window = new BoarderedWindow(); else window = new UnboarderedWindow(); } public void draw() { window.draw(); } } interface IWindow{ public void draw(); } class BoarderedWindow implements IWindow{ @Override public void draw() { System.out.println("boardered Window"); } } class UnboarderedWindow implements IWindow{ @Override public void draw() { System.out.println("unboardered Window"); } } 19
  • 21. 객체지향의 활용 Enum의 객체지향 특성을 활용하여 반복되는 코드를 제거한다. class Boundary{ int northLimit = 100; int southLimit = 50; int eastLimit = 20; int westLimit = 10; // getters public int getNorthLimit() { return northLimit; } public int getSouthLimit() { return southLimit; } public int getEastLimit() { return eastLimit; } public int getWestLimit() { return westLimit; } // setters public void setNorthLimit(int northLimit){ this.northLimit = northLimit; } public void setSouthLimit(int southLimit){ this.southLimit = southLimit; } public void setEastLimit(int eastLimit){ this.eastLimit = eastLimit; } public void setWestLimit(int westLimit){ this.westLimit = westLimit; } } class Boundary{ int[] boundaries = new int[Direction.values().length]; public int getLimit(Direction direction) { return boundaries[direction.ordinal()]; } public void setLimit( Direction direction, int limit) { boundaries[direction.ordinal()] = limit; } } enum Direction{ NORTH, SOUTH, EAST, WEST ; } 20
  • 22. 객체지향의 활용 불필요한 조건문이 발생하지 않도록 억제한다. class LineDrawer{ public void draw(){ System.out.println("line draw"); } } class Background{ LineDrawer lineDrawer = null; public void addLine(LineDrawer lineDrawer){ this.lineDrawer = lineDrawer; } public void draw(){ System.out.println("background draw"); } } class Use{ LineDrawer lineDrawer = null; Background background = null; public void setLineDrawer(LineDrawer lineDrawer) { this.lineDrawer = lineDrawer; } public void setBackground(Background background) { this.background = background; } public void draw(){ if(background != null) background.draw(); if(lineDrawer != null) lineDrawer.draw(); } } 21
  • 23. 객체지향의 활용 Special Case Pattern class LineDrawer{ public void draw(){ System.out.println("line draw"); } } class NullLineDrawer extends LineDrawer{ @Override public void draw(){} } class Background{ LineDrawer lineDrawer = null; public void addLine(LineDrawer lineDrawer){ this.lineDrawer = lineDrawer; } public void draw(){ System.out.println("background draw"); } } class NullBackground extends Background{ @Override public void draw(){} } class Use{ LineDrawer lineDrawer = new NullLineDrawer(); // Null을 대신하여 사용된 Null 객체 Background background = new NullBackground(); /* ……… */ public void draw(){ background.draw(); lineDrawer.draw(); } } 22
  • 24. 객체지향의 활용 enum에 의한 switch-case 문의 발생을 방지한다. enum PriceCode{ CHILDREN ,NORMAL ,NEW_RELEASE ; } class Use{ PriceCode priceCode = PriceCode.CHILDREN; public int getPrice(){ int price = 0; switch(priceCode){ case CHILDREN: price = 1000; break; case NORMAL : price = 1500; break; case NEW_RELEASE : price = 2000; break; default: price = 0; break; } return price; } } enum PriceCode{ CHILDREN{ public int getPrice(){ return 1000; } } ,NORMAL{ public int getPrice(){ return 1500; } } ,NEW_RELEASE{ public int getPrice(){ return 2000; } } ; abstract public int getPrice(); } class Use{ PriceCode priceCode = PriceCode.CHILDREN; public int getPrice(){ return priceCode.getPrice(); } } 23
  • 25. 객체지향의 활용 용도는 한가지인데 이용하는 변수가 여럿인 경우 class Table{ private int index; private int value; private int condition; public static final int BY_INDEX = 1; public static final int BY_VALUE = 2; public static final int BY_CONDITION = 3; private int coloringType; public void draw(){ if(coloringType == BY_INDEX){ Color color = byIndex(index); } else if(coloringType == BY_VALUE){ Color color = byValue(value); } else if(coloringType == BY_CONDITION){ Color color = byCondition(value); } } public Color byIndex(int index){ return null;} public Color byValue(int value){ return null;} public Color byCondition(int condition){ return null;} } 24
  • 26. 객체지향의 활용 “this” 참조를 넘겨 필요한 정보를 스스로 꺼내가도록 함. class Table{ private int index; private int value; private int condition; public int getIndex() { return index; } public int getValue() { return value; } public int getCondition() { return condition; } private Coloring coloring; public void draw(){ Color color = coloring.getColor(this); } } interface Coloring{ public Color getColor(Table table); } class ByIndex implements Coloring{ public Color getColor(Table table){ int index = table.getIndex(); return null; } } class ByValue implements Coloring{ public Color getColor(Table table){ int value = table.getValue(); return null; } } class ByCondition implements Coloring{ public Color getColor(Table table){ int condition = table.getCondition(); return null; } } 25