728x90

2025/03 4

[JAVA] Effective JAVA - Item 4 : Enforce noninstantiability with a private constructor

정적 메소드와 정적 필드는 보통 객체지향 개발에서 지양하는 방식이지만 다음 세가지 상황에서는 필요한 경우가 있다.1. 기본 타입 값이나 배열 관련 메소드들을 모아둘 때2. 특정 인터페이스를 구현하는 객체를 생성해주는 정적 메소드를 모아두고 싶을때3. final 클래스와 관련한 메소드를 모아둘 때 이런 정적 멤버만 담아둔 클래스는 인스턴스로 쓰려고 만든 것이 아니지만,컴파일러가 자동으로 기본 생성자를 만들어두고, 사용자는 이 생성자가 자동 생성자인지 구분이 안되는 이슈가 있다. 추상 클래스를 만들면 해결이 될 수 있다고 생각할수 있지만,하위 클래스를 만들어 인스턴스화를 해버리면 우회가 되기 때문에 이에 대한 근본적인 해결책이 아니다. 그렇다면 해결책은 무엇일까? 바로 private 생성자를 추가하는 것이다..

[JAVA] Effective JAVA - Item 3 : Enforce the singleton property with a privateconstructor or an enum type

what is 'Singleton'? A class that is instantiated exactly onceSingletons typically represent either a stateless object such as a function or system component that is intrinsically unique. The limit of singletons- Making a class a singleton can make it difficult to test its clients There are two common ways to implement singletons(Both are based on keeping the constructor private and exporting a ..

[JAVA] Effective JAVA - Item 2 : Consider a builder when faced with many constructor parameters

Case : scale well to large numbers of optional parameters-> static factories and contructors not good for this case then how to solve this case? The answer is : Builder Traditionally programmers have used the 'telescoping constructor'but, there have some problem Hard to write client codeHarder to read it and also you can say 'how about use JavaBeans'but there are still have some issues.Inconsist..

[JAVA] Effective JAVA - Item 1 : Consider static factory methods instead of constructor

The way for a class to allow a client to obtain an instance1. public contructors2. static factory method From now on, let me explain why we have to consider static factory methods instead of constructors. Advantage 1Static factory methods have names(unlike constructors) well-chosen name is good forEasier to useResulting client code easier to readEnd up calling the wrong one by mistakeAdvantage 2..

1
728x90
반응형