ITEM 1: Static Factory Method(정적 메소드)
Static Factory Method(정적 메소드)
// boolean의 기본 타입의 값을 받아 Boolean 객체 참조로 변환
public static Boolean valueOf(boolean b){
return b ? Boolean.TRUE : Boolean.FALSE;
}장점
public class Book { private String title; private String author; // 생성자1 public Book(String title, String author){ this.title = title; this.author = author; } /** * 생성자는 하나의 시그니처만 사용하므로, 다음과 같이 생성자 생성이 불가능하다. * */ public Book(String title){ this.title = title; } public Book(String author){ this.author = author; } }public class Book { String title; String author; public Book(String title, String author){ this.title = title; this.autor = author; } public Book(){} /* * withName, withTitle과 같이 이름을 명시적으로 선언할 수 있으며, * 한 클래스에 시그니처가 같은(String) 생성자가 여러개 필요한 경우에도 다음과 같이 생성할 수 있다. */ public static Book withAuthor(String author){ Book book = new Book(); book.author = author; return book; } public static Book withTitle(String title){ Book book = new Book(); book.title = title; return book; } }public final class Boolean implements java.io.Serializable, Comparable<Boolean> { /** * The {@code Boolean} object corresponding to the primitive * value {@code true}. */ public static final Boolean TRUE = new Boolean(true); /** * The {@code Boolean} object corresponding to the primitive * value {@code false}. */ public static final Boolean FALSE = new Boolean(false); // ... }// boolean의 기본 타입의 값을 받아 Boolean 객체 참조로 변환 public static Boolean valueOf(boolean b){ return b ? Boolean.TRUE : Boolean.FALSE; }// java7 Collections.emptyList() public Collections(){ ///... public static final List EMPTY_LIST = new EmptyList<>(); public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; } //... }// java9 List of() static <E> List<E> of() { return (List<E>) ImmutableCollections.ListN.EMPTY_LIST; }public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, java.io.Serializable { //... /** * Creates an empty enum set with the specified element type. * * @param <E> The class of the elements in the set * @param elementType the class object of the element type for this enum * set * @return An empty enum set of the specified type. * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { Enum<?>[] universe = getUniverse(elementType); if (universe == null) throw new ClassCastException(elementType + " not an enum"); if (universe.length <= 64) return new RegularEnumSet<>(elementType, universe); else return new JumboEnumSet<>(elementType, universe); } //... }
단점
주로 사용하는 명명 방식
메서드
설명
예제
참고
Last updated