Method

Static Factory Method

기본적으둜 Class 의 Instance λ₯Ό μ–»λŠ” 전톡적인 μˆ˜λ‹¨μ€ public μƒμ„±μžμ΄λ‹€.

ν΄λž˜μŠ€λŠ” μƒμ„±μžμ™€ λ³„λ„λ‘œ 정적 νŒ©ν† λ¦¬ λ©”μ„œλ“œ (static factory method) λ₯Ό 생성할 수 μžˆλ‹€.

μ‚¬μš©

class Character() {
  int strength, dexterity, consitution, intelligence;

  public Character(int strength, int dexterity, int consitution, int intelligence) {
    this.strength = strength;
    this.dexterity = dexterity;
    this.consitution = consitution;
    this.intelligence = intelligence;
  }

  public static Character newWarrior() {
    return new Character(15, 5, 10, 3);
  }

  public static Character newMage() {
    return new Character(3, 10, 5, 15);
  }
}
Character warrior = Character.newWarrior();
Character mage = Character.newMage();

μœ„ μ½”λ“œλŠ” 정적 νŒ©ν† λ¦¬ λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν•  λ•Œ λ§ˆλ‹€ new 연산을 ν•˜κ²Œ λ˜λŠ”λ°
immutable 객체λ₯Ό μΊμ‹œν•΄μ„œ μ“°κ³  μžˆκ±°λ‚˜ ν˜Ήμ€ μ•„λž˜μ™€ 같이 singleton design pattern 을 μ΄μš©ν•˜μ—¬ μ‚¬μš©λ„ κ°€λŠ₯ν•˜λ‹€.

class Person {
  private final Person p = new Person();

  public static Person getInstance() {
    return this.p;
  }
}

μ•„λž˜μ™€ 같이 λ¦¬ν„΄ν•˜λŠ” 클래슀의 νƒ€μž…μ„ μœ μ—°ν•˜κ²Œ 지정가λŠ₯ν•˜λ‹€.

class OrderUtil {
  public static Discount createDiscountItem(String code) throws Exception {
    if (!isValidCode(code)) {
      throw new Exception("Wrong discount code !!");
    }

    if (isCoupon(code)) {
      return new Coupon(1000);
      return new Point(500);
    }
  }
}

class Coupon extends Discount { ... }
class Point extends Discount { ... }

단점

  • 상속을 ν•˜λ €λ©΄ public μ΄λ‚˜ protected μƒμ„±μžκ° ν•„μš”ν•˜λ‹ˆ 정적 νŒ©ν† λ¦¬ λ©”μ„œλ“œλ§Œ μ§€μ›ν•˜λ©΄ ν•˜μœ„ 클래슀λ₯Ό λ§Œλ“€μˆ˜ μ—†λ‹€.
  • 정적 νŒ©ν† λ¦¬ λ©”μ„œλ“œλŠ” ν”„λ‘œκ·Έλž˜λ¨Έκ°€ μ°ΎκΈ° μ–΄λ ΅λ‹€.
    • μ•”λ¬΅μ μœΌλ‘œ λŒ€ν‘œμ μΈ λͺ…λͺ… κ·œμΉ™λ“€μ— μ˜ν•΄ λ©”μ„œλ“œ 넀이밍을 ν•˜λŠ”κ²ƒμ΄ μΌλ°˜μ μ΄λ‹€.
    • from, of, valueOf, instance, getInstance, create, getType ...

getClass λž€ ?

Object Class 의 λ©”μ„œλ“œλ‘œμ„œ Object Class λ₯Ό 상속 λ°›λŠ” μžμ‹ ν΄λž˜μŠ€μ—μ„œ μ‚¬μš© κ°€λŠ₯ν•œ λ©”μ„œλ“œ 이닀.

  • getClass()
    • 객체가 μ†ν•˜λŠ” 클래슀의 정보λ₯Ό μ•Œμ•„λ‚΄λŠ” λ©”μ†Œλ“œμ΄λ‹€.
  • getName()
    • 클래슀의 이름을 λ¦¬ν„΄ν•˜λŠ” λ©”μ†Œλ“œμ΄λ‹€.
  • getSuperclass()
    • 슈퍼 클래슀의 정보λ₯Ό λ¦¬ν„΄ν•˜λŠ” λ©”μ†Œλ“œμ΄λ‹€.
  • getDeclaredFields()
    • ν΄λž˜μŠ€μ— μ„ μ–Έλ˜μ–΄ μžˆλŠ” ν•„λ“œ 정보λ₯Ό κ°€μ Έμ˜€λŠ” λ©”μ†Œλ“œμ΄λ‹€.
  • getDeclaredMethod()
    • ν΄λž˜μŠ€μ— μ„ μ–Έλ˜μ–΄ μžˆλŠ” λ©”μ†Œλ“œ 정보λ₯Ό κ°€μ Έμ˜€λŠ” λ©”μ†Œλ“œμ΄λ‹€.

참고자료

https://zzdd1558.tistory.com/57