https://inpa.tistory.com/entry/GOF-💠-정적-팩토리-메서드-생성자-대신-사용하자
public 생성자를 사용해 객체를 생성하는 방법 외 다음과 같이 public 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;
}
}
생성자는 똑같은 타입의 파라미터로 받는 생성자를 여러개 생성할 수 없음
static factory method는 한 클래스에 시그니처가 같은 생성자가 여러 개 필요한 경우에도 사용할 수 있으며, 또한, 파라미터가 반환하는 객체를 잘 설명하지 못하는 경우에, 이름을 잘 지은 static factory method를 사용할 수 있음
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;
}
불변클래스 : 미리 만들어둔 인스턴스를 재활용하여(캐싱) 불필요한 객체 생성을 피할 수 있음
Boolean.TRUE
는 이에 대한 대표적인 예로, 객체를 생성하지 않음
Flyweight pattern : 데이터를 공유해 메모리를 절약하는 패턴으로 공통으로 사용되는 객체는 한번만 사용되고, pool에 의해서 관리, 사용됨
https://inpa.tistory.com/entry/GOF-💠-Flyweight-패턴-제대로-배워보자
<aside>
💡 **플라이웨이트 패턴(Flyweight Pattern)
**은 재사용 가능한 객체 인스턴스를 공유시켜 메모리 사용량을 최소화하는 구조 패턴
간단히 말하면 캐시(Cache) 개념을 코드로 패턴화 한것으로 보면 되는데, 자주 변화는 속성(extrinsit)과 변하지 않는 속성(intrinsit)을 분리하고 변하지 않는 속성을 캐시하여 재사용해 메모리 사용을 줄이는 방식이다. 그래서 동일하거나 유사한 객체들 사이에 가능한 많은 데이터를 서로 공유하여 사용하도록 하여 최적화를 노리는경량 패턴이라고도 불린다.
</aside>
Instance-Controlled Class : 정적 펙토리 방식의 클래스는 언제 어느 인스턴스를 살아 있게 할지 통제할 수 있음
리턴 타입의 하위 타입 객체를 반환할 수 있음
// 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;
}
입력 매개변수에 따라 매번 다른 클래스의 객체를 반환할 수 있음
하위 타입 클래스이기만 하면 어떠한 클래스의 객체를 반환할 수 있음
그 대표적인 예가 EnumSet
으로, public 생성자 없이 오직 정적 팩터리만으로 제공
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);
}
//...
}
EnumType의 원소의 개수에 따라 RegularEnumSet
, JumboEnumSet
으로 결정되는데 클라이언트는 이 두 객체의 존재를 모르며, 추후에 새로운 타입을 만들거나 기존 타입을 없애는 경우에도 문제되지 않음
정적 팩토리 메소드를 작성하는 시점에는 반환할 객체의 클래스가 존재하지 않아도 됨
Connection
) : 구현체의 동작 정의DriverManager.registerDriver
) : provider가 구현체를 등록할 때 사용DriverManager.getConnection
) : 클라이언트는 서비스 접근 API 사용시 원하는 구현체의 조건을 명시할 수 있음Driver
) : 서비스 인터페이스의 인스턴스를 생성하는 펙토리 객체를 설명해준다.