~lovesyao/+junk/transgs

« back to all changes in this revision

Viewing changes to nazo/singleton.d

  • Committer: Nazo
  • Date: 2008-10-18 08:26:14 UTC
  • Revision ID: lovesyao@hotmail.com-20081018082614-22qgtg2gsotz5r2i
initial checkin

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
module nazo.singleton;
 
2
/**
 
3
 * デザインパターン、Singletonに簡単に対応します。
 
4
 * History:
 
5
 *          0.0.0.1 作成
 
6
 * Authors: Nazo
 
7
 * Version: 0.0.0.1
 
8
 * License: Public Domain
 
9
 */
 
10
///初めてgetInstanceが呼ばれたときにインスタンスを作成
 
11
class Singleton(T){
 
12
  private static T instance;
 
13
  private this(){};
 
14
  synchronized public static T getInstance(){
 
15
    if(instance is null)
 
16
      instance = new T();
 
17
    return instance;
 
18
  }
 
19
}
 
20
 
 
21
///mainの前にインスタンスを作成
 
22
class Singleton2(T){
 
23
  private static T instance;
 
24
  private this(){};
 
25
  public static T getInstance(){
 
26
    return instance;
 
27
  }
 
28
  synchronized static this(){
 
29
      instance = new T();
 
30
  }
 
31
}
 
32
 
 
33
class Test:Singleton!(Test){}
 
34
class Test2:Singleton2!(Test){}
 
35
 
 
36
unittest{
 
37
  assert(Test.getInstance()==Test.getInstance());
 
38
  assert(Test2.getInstance()==Test2.getInstance());
 
39
}