티스토리 뷰
Factory Method Pattern
- 팩토리 객체는 공통 인터페이스 타입 객체를 만드는 팩토리 메소드를 가지고 있다.
- 외부에서 특정 타입 및 파라미터를 받으면 해당 타입에 맞는 팩토리를 호출하여 객체를 생성한다.
public enum WeaponType {
SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
private String title;
WeaponType(String title) {
this.title = title;
}
}
public class OrcWeapon implements Weapon {
private WeaponType weaponType;
public OrcWeapon(WeaponType weaponType) {
this.weaponType = weaponType;
}
@Override
public String toString() {
return "Orcish " + weaponType;
}
@Override
public WeaponType getWeaponType() {
return weaponType;
}
}
public class ElfWeapon implements Weapon {
private WeaponType weaponType;
public ElfWeapon(WeaponType weaponType) {
this.weaponType = weaponType;
}
@Override
public String toString() {
return "Elven " + weaponType;
}
@Override
public WeaponType getWeaponType() {
return weaponType;
}
}
public interface Weapon {
WeaponType getWeaponType();
}
public class OrcBlacksmith implements Blacksmith {
public Weapon manufactureWeapon(WeaponType weaponType) {
return new OrcWeapon(weaponType);
}
}
public class ElfBlacksmith implements Blacksmith {
public Weapon manufactureWeapon(WeaponType weaponType) {
return new ElfWeapon(weaponType);
}
}
public interface Blacksmith {
Weapon manufactureWeapon(WeaponType weaponType);
}
public class App {
private final Blacksmith blacksmith;
public App(Blacksmith blacksmith) {
this.blacksmith = blacksmith;
}
public static void main(String[] args) {
App app = new App(new OrcBlacksmith());
app.manufactureWeapons();
app = new App(new ElfBlacksmith());
app.manufactureWeapons();
}
private void manufactureWeapons() {
Weapon weapon;
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon.toString());
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
System.out.println(weapon.toString());
}
}
'Programming > 디자인 패턴' 카테고리의 다른 글
Observer Pattern (0) | 2019.01.24 |
---|---|
Builder Pattern (0) | 2019.01.24 |
Template Method Pattern (0) | 2019.01.24 |
Strategy Pattern (0) | 2019.01.24 |
- Total
- Today
- Yesterday
- Discriminate Mapping
- @Primary
- Akka
- Spring Registrar
- Registrar
- Query DSL
- Charles proxy
- Spring JDBC Template
- java Equals
- scikit-learn
- Embeddable Mapping
- java generic
- Spring
- java EqualsAndHashCode
- docker
- Sprint RetryTemplate
- SmartLifecycle
- Property
- spring spel
- JPA Criteria
- Join Table
- guava
- JPA
- Mapping
- Criteria
- RetryTemplate
- DI
- 복합키 Mapping
- Typesafe Config
- Embedded Mapping
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |