Twitter @m_hiyama 
Follow @m_hiyama

 hiyama{at}chimaira{dot}org 



 

DI(依存性注入)を白紙から説明してみる


DI 1


DI


[DI] 
 

DIDependency Injection; 使




(一)

(二)

(三)使

(四)

(五)

(六)DI

(七)DIIoC



Xionhttp://www.chimaira.org/tmp/Xion-0.1.tgz

Very Simple Templates; VST

{お客様名}様、こんにちは。{来店日}にはご来店いただき、
まことにありがとうございます。
本日は{お客様名}様に新商品をご紹介いたします。
{}{}

2


(一)

(二)


VSTSAXSimple API for XML()使quick-and-dirty


VSTLexer.java

VSTParser.java



VSTParserVSTLexer使'{'left brace'}'right braceEOFend-of-filenextTokenVSTToken


/* トークン・データ */
class VSTToken {
enum Kind {L_BRACE, R_BRACE, TEXT, EOF}

final Kind kind;
final String value;
VSTToken(Kind kind, String value) {
this.kind = kind;
this.value = value;
}
}





'{''}'

unescape

'{''}'



valuenull""


'{''{{'2使

使


parse

public void parse(Reader input) throws IOException, VSTParseException {
VSTLexer lexer = new VSTLexer(input);
// ...
}


VSTParserVSTLexer -- VSTLexerinput便setInput*1


import java.io.*;

interface VSTLexer {
public void setInput(Reader reader);
public VSTToken nextToken() throws IOException;
}



VSTLexerVSTLexerStdImpl

new使

public void parse(Reader input) throws IOException, VSTParseException {
VSTLexerFactory factory = new VSTLexerFactory("some parameter");
VSTLexer lexer = factory.create(input);
// ...
}


setInput

// レクサーの生成は、パーザーのコンストラクタ内でもよい
VSTLexerFactory factory = new VSTLexerFactory("some parameter");
VSTLexer lexer = factory.create();
// 後からinputをセットできるからね
lexer.setInput(input);



service locator


public void parse(Reader input) throws IOException, VSTParseException {
VSTLexer lexer = null;
MyServiceLocator locator = MyServiceLocator.getInstance();
try {
lexer = (VSTLexer)locator.getService(VSTLexer.class);
} catch (Exception e) {
// エラー処理
}
lexer.setInput(input);
// ...
}





使VSTLexerFactoryMyServiceLocator

VSTLexerFactoryMyServiceLocator使

VSTLexerFactoryMyServiceLocator使VSTLexerFactoryMyServiceLocatorVSTLexerFactoryMyServiceLocator

DI













class VSTParser {
public VSTLexer lexer; // ここにダレカサンがセットしてくれる
// ....
}



class VSTParser {
private VSTLexer lexer;
// このメソッドをダレカサンが呼んでくれる
public void setLexer(VSTLexer lexer) {
this.lexer = lexer;
}
// ....
}




DIIoC


Inversion of Control  Dependency Injection DIIoCInversion of Control; 

 responsibilityIoR








VSTLexer lexer = factory.create();

lexer = (VSTLexer)locator.getService(VSTLexer.class);







*1:ポートベース・コンポネントの発想では、setInputはレクサー機能を表すインターフェースの一部というよりむしろ、ポート間のワイヤリング機構だと考えます。