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
...
κ΄λ ¨μΆμ² - Effective Java 3rd
https://johngrib.github.io/wiki/static-factory-method-pattern/
https://mommoo.tistory.com/53
getClass
λ ?
Object Class
μ λ©μλλ‘μ Object Class
λ₯Ό μμ λ°λ μμ ν΄λμ€μμ μ¬μ© κ°λ₯ν λ©μλ μ΄λ€.
- getClass()
- κ°μ²΄κ° μνλ ν΄λμ€μ μ 보λ₯Ό μμλ΄λ λ©μλμ΄λ€.
- getName()
- ν΄λμ€μ μ΄λ¦μ 리ν΄νλ λ©μλμ΄λ€.
- getSuperclass()
- μνΌ ν΄λμ€μ μ 보λ₯Ό 리ν΄νλ λ©μλμ΄λ€.
- getDeclaredFields()
- ν΄λμ€μ μ μΈλμ΄ μλ νλ μ 보λ₯Ό κ°μ Έμ€λ λ©μλμ΄λ€.
- getDeclaredMethod()
- ν΄λμ€μ μ μΈλμ΄ μλ λ©μλ μ 보λ₯Ό κ°μ Έμ€λ λ©μλμ΄λ€.
μ°Έκ³ μλ£