Open-Closed Principle
Open for extension
확장에는 열려있되,
Closed for modification
수정엔 닫혀있어야 한다.
이게 무슨 의미냐.
새로운 기능 추가나 변경사항은 자유롭게 할 수 있고,
기존의 코드는 건들지 않아도 되는 구조를 말한다.
기존 개발되어 있는 부분에 추가적인 기능을 넣는 나의 업무에 필수적인 원칙이다.
강의의 예시 구조 이미지를 발췌해보겠다.
이러한 경우 Driver 클래스의 코드는 수정할 필요가 없다.
새로 Car를 추가해야 하거나 Car에 기능을 추가해야할 때도 Driver 클래스의 코드는 수정될 필요가 없다.
=> Closed for modification
그저 새로운 Car를 implement하는 클래스를 만들어 실행하면 된다.
=> Open for extension
+) 전략 패턴
행동을 클래스화하고 행동의 구현을 변경할 수 있게 하여 동적으로 행동을 바꿀 수 있도록 하는 디자인 패턴이다.
= 특정 작업을 다양한 알고리즘으로 분리하여 교체 가능하게 만드는 디자인 패턴
키워드: 캡슐화, 교체
전략 패턴의 구성 요소
- Strategy Interface: 알고리즘을 정의하는 인터페이스.
- Concrete Strategy Classes: Strategy 인터페이스를 구현하는 여러 알고리즘 클래스.
- Context: Strategy 인터페이스를 이용하는 클래스.
정렬 알고리즘에 대한 자바 예시
1.Strategy Interface (SortingStrategy): 정렬 알고리즘을 정의하는 인터페이스
public interface SortingStrategy {
void sort(int[] numbers);
}
2. Concrete Strategy Classes (BubbleSortStrategy, QuickSortStrategy): 정렬 알고리즘을 각각 구현한 클래스.
public class BubbleSortStrategy implements SortingStrategy {
@Override
public void sort(int[] numbers) {
int n = numbers.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
// swap arr[j] and arr[j+1]
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
System.out.println("Sorted using Bubble Sort");
}
}
public class QuickSortStrategy implements SortingStrategy {
@Override
public void sort(int[] numbers) {
quickSort(numbers, 0, numbers.length - 1);
System.out.println("Sorted using Quick Sort");
}
private void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
}
3. Context (SortContext): SortingStrategy 인터페이스를 사용하여 정렬을 수행하는 클래스. 전략을 동적으로 변경할 수 있는 메서드를 제공.
public class SortContext {
private SortingStrategy strategy;
public SortContext(SortingStrategy strategy) {
this.strategy = strategy;
}
public void setStrategy(SortingStrategy strategy) {
this.strategy = strategy;
}
public void sortArray(int[] numbers) {
strategy.sort(numbers);
}
}
4. main()
public class StrategyPatternDemo {
public static void main(String[] args) {
int[] numbers = { 5, 2, 9, 1, 5, 6 };
SortContext context = new SortContext(new BubbleSortStrategy());
context.sortArray(numbers);
// Output: Sorted using Bubble Sort
context.setStrategy(new QuickSortStrategy());
context.sortArray(numbers);
// Output: Sorted using Quick Sort
}
}
'Language > Java' 카테고리의 다른 글
[Java] 동시성 문제, 쓰레드 로컬 ThreadLocal (1) | 2023.11.30 |
---|---|
Java 필수 - 멀티쓰레드와 동기화 (feat. Atomic, Synchronized, Volatile) (0) | 2023.07.03 |
Java 기본 - Wrapper Class 래퍼 클래스 (0) | 2023.06.30 |
Java 기본 - 접근자 (0) | 2023.06.30 |
Java 기본 - 오버라이딩 오버로딩 (0) | 2023.06.29 |