Chain Constructors (연쇄 생성자)

Posted by epicdev Archive : 2012. 1. 24. 23:04
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
public class Dice {
    private static final long DEFAULT_SEED = 12345L;
    private Random rand;
     
    public Dice() {
        // rand = new Random(DEFAULT_SEED);
        this(DEFAULT_SEED);
    }
     
    public Dice(long seed) {
        rand = new Random(seed);
        System.out.println("Seed: " + seed);
    }
     
    public int roll() {
        return rand.nextInt(6) + 1;
    }
     
    public static void main(String[] args) {
        Dice dice = new Dice();
        for(int i = 0; i < 10; i++) {
            System.out.println(dice.roll());
        }
    }
}

디폴트 생성자에서 rand = new Random(DEFAULT_SEED);를 호출하지 않고
long seed를 인자로 받는 다른 생성자를 호출하는 방식을 통해 중복되는 코드를 피하고 있다.