1. Framework
- Product 클래스 : '제품'을 표현한 추상 클래스로서 추상 메서드 use만 선언 되어 있다.
package com.sgdata.factorymethod;
public abstract class Product {
public abstract void use();
}
- Factory 클래스 : 템플릿 패턴이 적용되어 있습니다. 추상 메서드 createProduct,registerProduct는 하위 클래스에서 구현 합니다.
package com.sgdata.factorymethod;
public abstract class Factory {
public final Product create(String owner) {
Product p = createProduct(owner);
registerProduct(p);
return p;
}
protected abstract Product createProduct(String owner);
protected abstract void registerProduct(Product product);
}
2. Idcard
- IDCard 클래스 : Product 클래스를 상속받아서 구현.
package com.sgdata.factorymethod;
public class IDCard extends Product{
private String owner;
private int serial;
IDCard(String owner, int serial){
System.out.println(owner +"("+serial+")"+"의 카드를 만듭니다.");
this.owner = owner;
this.serial = serial;
}
@Override
public void use() {
// TODO Auto-generated method stub
System.out.println(owner + "(" + serial +")" +"의 카드를 사용합니다.");
}
public String getOwner(){
return owner;
}
public int getSerial(){
return serial;
}
}
- IDCardFactory : Factory 클래스를 상속받아서 구현.
package com.sgdata.factorymethod;
import java.util.HashMap;
import java.util.Hashtable;
public class IDCardFactory extends Factory{
private HashMap database = new HashMap();
private int serial = 100;
@Override
protected synchronized Product createProduct(String owner) {
// TODO Auto-generated method stub
return new IDCard(owner, serial++);
}
@Override
protected void registerProduct(Product product) {
// TODO Auto-generated method stub
IDCard card = (IDCard)product;
database.put(new Integer(card.getSerial()), card.getOwner());
}
public HashMap getDatabase(){
return database;
}
}
3. Main
package com.sgdata.factorymethod;
public class Main {
public static void main(String[] args) {
Factory factory = new IDCardFactory();
Product card1 = factory.create("홍길동");
Product card2 = factory.create("김민수");
Product card3 = factory.create("구로이드");
card1.use();
card2.use();
card3.use();
}
}