디자인 패턴
- Factory Pattern: 객체 생성을 추상화하여, 유연성을 높이는 패턴.
- Strategy Pattern: 알고리즘을 캡슐화하여, 동적으로 교체할 수 있도록 하는 패턴.
- Singleton Pattern: 특정 클래스의 instance가 단 하나만 생성되도록 보장하는 패턴.
- Prototype Pattern: 새로운 객체를 생성할 때, 기존 객체를 복제하여 사용하는 방식으로 동작하는 패턴.
Factory Pattern 예시 코드
1. interface 생성
public interface Shape {
void draw();
}
2. interface를 구현한 클래스 생성
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square");
}
}
3. Factory 생성
- Shape 객체 생성을 하는 Factory 생성.
- equalsIgnoreCase(): 문자열의 대소문자를 구분하지 않고 두 문자열이 같은지를 비교
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
4. main 함수 생성
- main 함수에서 직접 객체를 생성하지 않고, Factory를 이용해서 객체 생성.
public class Main {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of square
shape3.draw();
}
}
Strategy Pattern 예시 코드
1. interface 생성
public interface Strategy {
public int doOperation(int num1, int num2);
}
2. interface를 구현한 클래스 생성
public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class OperationMultiply implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
public class OperationSubstract implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
3. Context 생성
- 알고리즘을 실행하는 객체 구현.
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
4. main 함수 생성
- Context의 알고리즘이 Strategy에 따라 바뀜.
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
Singleton Pattern 예시 코드
1. Singleton 클래스 생성
public class SingleObject {
//create an object of SingleObject
private static final SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject() {
}
//Get the only object available
public static SingleObject getInstance() {
return instance;
}
public void showMessage() {
System.out.println("Hello World!");
}
public void showHashCode() {
System.out.println(this.hashCode());
}
}
2. main 함수 생성
- 항상 같은 클래스만 반환함
public static void main(String[] args) {
// Compile Time Error. constructor is private
// SingleObject object = new SingleObject();
SingleObject object1 = SingleObject.getInstance();
object1.showMessage();
object1.showHashCode();
SingleObject object2 = SingleObject.getInstance();
object2.showMessage();
object2.showHashCode();
}
참고: 2024.08.31 - [NHN Java 백엔드 8기/Java] - [Java] Singleton 패턴
[Java] Singleton 패턴
Singleton 패턴 Class의 Instance가 오직 하나임을 보장, 정의된 접근 방식에 의해서만 접근. Singleton의 instance인 singleton을 private static으로 선언 후, 생성자를 priavate로 선언해서 생성 불가능하게 한다.
lightningtech.tistory.com
Prototype Pattern 예시 코드
- 요청할 때마다 새로운 instance를 생성해서 반환.
참고: 2024.09.08 - [NHN Java 백엔드 8기/Java 연습 문제] - [Java 연습문제] Singleton과 Prototype 리포지토리 *
[Java 연습문제] Singleton과 Prototype 리포지토리 *
Singleton과 Prototpye 리포지토리GoF 디자인 패턴 중, 생성 패턴에 속하는 ProtoType 패턴은 코드를 클래스들에 의존시키지 않고 기존 객체들을 복사할 수 있도록 하는 패턴입니다.객체가 있고
lightningtech.tistory.com
출처: https://nhnacademy.dooray.com/share/pages/ABFgz8KgRv62A85x9KClUw
Spring Boot Core
nhnacademy.dooray.com
참고
https://www.tutorialspoint.com/design_pattern
Design Patterns in Java Tutorial
Design Patterns in Java Tutorial - Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These sol
www.tutorialspoint.com
2024.09.08 - [NHN Java 백엔드 8기/Java 연습 문제] - [Java 연습문제] Singleton과 Prototype 리포지토리 *
[Java 연습문제] Singleton과 Prototype 리포지토리 *
Singleton과 Prototpye 리포지토리GoF 디자인 패턴 중, 생성 패턴에 속하는 ProtoType 패턴은 코드를 클래스들에 의존시키지 않고 기존 객체들을 복사할 수 있도록 하는 패턴입니다.객체가 있고
lightningtech.tistory.com
'Spring' 카테고리의 다른 글
[Spring Boot] 01. Spring Boot Core (3) - AOP(관점 지향 프로그래밍) * (0) | 2024.11.08 |
---|---|
[Spring Boot] @ConfigurationProperties 활성화시 @Profile 무시 에러 (0) | 2024.11.08 |
[Spring Boot] 01. Spring Boot Core (2) - 자동 구성과 외부 구성 (0) | 2024.11.06 |
[Spring Boot] Lombok (0) | 2024.11.06 |
[Spring Boot] 01. Spring Boot Core (1) - Spring Boot 소개, IoC, DI (3) | 2024.11.05 |