JavaでHello World
Google
  HOME  |  基礎  |  掲示板  |  ツール |  書籍  |  デザインパターン  |  リンク  |  フィードバック
JavaでHello World > デザインパターン > Singletonパターン  
メニュー
Home
情報交換掲示板
Factory Method
Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Chain Of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
  2003/07/25  田中宏和
Singletonパターン
◆概要
クラスが1つだけインスタンスを持つことを保証し、そのインスタンスにアクセスするためのグローバルな方法を提供する
◆UML
◆ここでの環境
OS Windows XP
J2SE SDK 1.4.1_01
◆概念的なソースコード
Singleton.java(ここからダウンロード)
public class Singleton {
  private static Singleton instance;

  private Singleton() {
  }

  public static synchronized Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}
Client.java(ここからダウンロード)
public class Client {
  public static void main(String[] args) {
    Singleton s1 = Singleton.getInstance();
    Singleton s2 = Singleton.getInstance();

    if (s1 == s2) {
      System.out.println("同じインスタンスです");
    }
  }
}
 
◆実行
コマンドプロンプト
C:\JavaHello\Singleton>javac *.java

C:\JavaHello\Singleton>java Client
同じインスタンスです

C:\JavaHello\Singleton>

おおおお!実行できましたね!

 
 
  ネットで買えば断然お得!お買い物なら楽天市場
ツールの部屋 - Java関連の書籍 - デザインパターン - 情報交換掲示板 - HOME