1. 팩토리 메소드 패턴
1. 팩토리 메소드 패턴
데코레이터 패턴
- 기본 추상구성요소를 가지고 기능을 추가 및 수정
생성자
FileInputStream(File file)
FilterInputStream(InputStream in)
LineNumerInputStream(InputStream in)
Ex) InputStream in =
LineNumerInputStream(new BufferedInputStream(new FileInputStream(file)))
1. FileInputStream = 데코레이터로 포장될 구성요소 -> 파일을 읽어들임
2. BufferedInputStream = 구상데코레이터 -> 속도향상(buffer사용), 한줄씩 읽어들이는 readLine() 메소드 제공
3. LineNumberInputStream = 구상데코레이터 -> 행번호를 붙여줌
ex) 자바 I/O
아이터레이터 패턴
싱글톤 패턴
1. public class Singleton { => 매번 동기화 해야 하기 때문에 속도가 느림
private static Singleton uniqueInstance;
// 기타 인스턴스 변수
private Singleton() {}
public static synchronized Singleton getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// 기타 메소드
}
2. public class Singleton { => 처음부터 메모리를 소비하고 속도를 높일 수 있음
private static Singleton uniqueInstance = new Singleton();
// 기타 인스턴스 변수
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
// 기타 메소드
}
3. public class Singleton { => 속도와 메모리 두 마리 토끼 잡기
private volatile static Singleton uniqueInstance;
// 기타 인스턴스 변수
// volatile은 언제나 최신값을 가짐(두가지 특징)
// 1. Thread에 변수가 공유되면 각자의 Caching 값을 같고 있다 업데이트 하지만 volatile 변수의 경우
// Caching 하지 않고 바로 메인모메로 영역의 변수로 접근한다.
// 2. 동기화를 지원하여 동시에 여러게의 Thread가 접근할 수 없다.
private Singleton() {}
public static Singleton getInstance() {
if(uniqueInstance == null) { <= 처음에만 동기화하고 다음에는 접근하지 않음
synchronized (Singleton.class) {
if(uniqueInstance == null) { <= Double-checking locking
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
// 기타 메소드
}