언어
-
이펙티브 자바 Item6 - 불필요한 객체 생성을 피하라언어/Effective Java 2024. 5. 27. 16:35
불필요한 객체 생성을 피하면서 자원을 절약해야한다.같은 기능의 객체를 새로 생성하는 대신, 객체 하나를 재사용하는 편이 나을 때가 많다.특히, 불변 객체는 언제든지 재사용할 수 있다. 같은 기능 수행하는 객체에 대한 재사용 강조싱글톤 사용 (내가 구현할 때)static factory 메서드 사용 (구현된 것을 사용할 때)객체 캐싱 (무거운 객체일 때 미리 초기화 혹은 flyweight 패턴 고려) 같은 인스턴스 대변하는 여러 타입을 굳이 만들지 말 것 박싱 클래스는 꼭 필요한 경우만 사용 1. 문자열 객체 생성 같은 값임에도 다른 래퍼런스인 경우 - 기존 인스턴스를 재사용하자 문자열의 경우 항상 new 로 새로운 문자열을 생성하기 보다 같은 문자열이라면, "java"처럼 리터럴로 생성한다. 2. s..
-
이펙티브 자바 Item5 - 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라언어/Effective Java 2024. 5. 27. 15:54
사용하는 자원에 따라 동작이 달라지는 클래스는 정적 유틸리티 클래스나 싱글턴 방식이 적합하지 않다. 1. 자원 직접 주입 대부분의 클래스는 여러 리소스에 의존한다. 책에서는 SpellChecker와 Dictionary를 예로 든다.두 객체 사이에는 의존관계가 있다. 아래는 static 유틸리티를 잘못 사용한 예이다. - 이는 유연하지 않고 테스트가 어렵다.public class SpellChecker { private static final Lexicon dictionary = ...; // 의존하는 리소스 (의존성) private SpellChecker() {} // 객체 생성 방지 public static boolean isValid(String word) { ... } public static..
-
이펙티브 자바 Item3 - private 생성자나 열거타입으로 싱글톤임을 보장하라언어/Effective Java 2024. 5. 27. 15:18
싱글톤이란, 인스턴스를 오직 하나만 생성할 수 있는 클래스를 의미한다.싱글톤을 사용하는 클라이언트는 테스트가 어렵다. 하나의 자원을 공유하기 때문에 테스트로 써도 되는 클래스인가를 판별해야하기 때문이다. (ex DB 접근하는 싱글톤을 테스트에 적용하면 안된다) 서버 환경에서는 싱글톤이 하나만 만들어지는 것을 보장하지 못한다.서버에서 클래스 로더를 어떻게 구성하고 있느냐에 따라 JVM이 분산되어 여러개 있을 경우 싱글톤 클래스임에도 불구하고 하나 이상의 오브젝트가 만들어질 수 있다.싱글톤의 사용은 전역 상태를 만들 수 있기 때문에 바람직하지 못하다.아무 객체나 자유롭게 접근하고 수정하고 공유할 수 있는 전역 상태를 갖는 것은 객체지향 프로그래밍싱글톤을 만드는 방식 1.public static 멤버가 fin..
-
이펙트브 자바 Item4 - 인스턴스화를 막으려거든 private 생성자를 사용하라언어/Effective Java 2024. 5. 27. 12:24
자바는 생성자를 선언하지 않으면, 기본으로 default 생성자를 만든다. (매개변수 x 생성자)따라서, 생성자를 안만든다고 객체를 못만드는 것은 아니다. 객체를 생성하기 싫다면, private 생성자를 통해 이를 반드시 막아라 * * This class contains various methods for manipulating arrays (such as * sorting and searching). This class also contains a static factory * that allows arrays to be viewed as lists. */// Suppresses default constructor, ensuring non-instantiability.private Arrays() ..
-
이펙티브 자바 Item2 - 생성자에 매개변수가 많다면 빌더를 고려하라언어/Effective Java 2024. 5. 27. 11:44
정적 팩토리와 생성자는 "선택적 매개변수"가 많을 때 적절하게 대응하기 어렵다는 단점이 있다. 만약 있을 수도 없을 수도 있는 필드가 많은 객체가 있다고 한다면.. 1. 점층적 생성자 패턴 필수 매개변수를 받는 생성자 1개, 그리고 선택 매개변수를 하나씩 늘려가며 생성자를 만드는 패턴이다. public class Javabom { private Long id; private List members; private String email; private LocalDateTime createDateTime; private boolean isOpen; public Javabom(Long id, List members, String email, LocalDateTime crea..
-
이팩티브 자바 Item 1 - 생성자 대신 정적 팩터리 메서드를 고려하라언어/Effective Java 2024. 5. 27. 11:06
인스턴스를 생성하는 방법은 (1) public 생성자 (2) 정적 팩터리 메서드 사용이 있다. 이때, 정적 팩터리 메서드 메서드를 사용하면 다음과 같은 장점이 있다.1. 생성 목적에 대한 이름 표현이 가능하다. (객체 생성의 가독성이 높아진다) 생성자는 클래스명으로만 구현할 수 있지만, 정적팩터리 메서드는 자신의 이름을 가질 수 있다.new 키워드를 통해 생성자를 생성하면, 해당 생성자의 인수 순서와 내부구조를 알고 있어야 목적에 맞게 객체를 생성할 수 있다는 번거로움 존재정적 팩터리 메서드 구현 시 자주 사용되는 이름이 있다! from: 매개변수를 받아서 해당 타입의 인스턴스 반환of: 여러 매개변수 받아서 적합한 인스턴스 반환valueOf : from, of보다 자세한 버전 instance, get..
-
템플릿 메서드(Template Method) 패턴언어/디자인패턴 2024. 5. 26. 22:31
템플릿 메서드 패턴이란? 여러 클래스에서 공통으로 사용하는 메서드를 템플릿화하여 상위 클래스에서 정의하고, 하위 클래스마다 세부 동작 사항을 다르게 구현하는 패턴이다.변하지 않는 기능은 상위 클래스에 만들어두고 자주 변경되어 확장할 기능은 하위 클래스에서 만들도록 하는 것이다.상속이라는 기술을 극대화하여, 알고리즘의 뼈대를 맞추는 것에 초점을 둔다. 공통된 부분에서 다른 부분 혹은 확장 가능한 부분을 제공하는 느낌! (공통을 따로 뺀다는 느낌보다 공통은 그대로 두고, 바뀌는 부분만 새로 만들도록 한다!) AbstractClass(추상 클래스) : 템플릿 메소드를 구현하고, 템플릿 메소드에 돌아가는 추상 메서드를 선언한다. 이 추상 메서드는 하위클래스 ConcreateClass에서 구현된다.Concrete..
-
전략 패턴 (Strategy)언어/디자인패턴 2024. 5. 26. 21:41
전략 패턴이란?실행(런타임) 중 알고리즘 전략을 선택하여 객체 동작을 실시간으로 바뀌도록 하는 행위 디자인 패턴이다.전략은 일종의 알고리즘 혹은 특정 목표를 수행하기 위한 행동 계획을 의미한다.어떤 일을 수행하는 알고리즘이 여러가지 일때, 동작들을 미리 전략으로 정의하여, 손쉽게 교체하는 방법이다. 알고리즘 변형이 빈번할 경우 적합하다. 전략 인터페이스 : 모든 전략 구현체에 대한 공용 인터페이스 전략 객체(concreate): 전략 인터페이스 구현체 컨텍스트(Context) : 알고리즘을 실행할 때 해당 알고리즘과 연결된 전략 객체 메서드 호출 (전략을 사용하는 큰 기능)클라이언트 : 전략 객체 전달, 해당 전략 사용해서 결과 얻음class Client{ public static void main(St..