SlideShare uma empresa Scribd logo
1 de 42
Baixar para ler offline
Dependency
Injectionとは
doi
依存とは
Dependency
依存とは
• 僕はパソコンが無いと生きていけない
• 僕はパソコンに依存
• ネットがないと僕は生きていけない
• 僕はネットとパソコンが無いと

成立しない状態
例えば
Code
class Enemy
{
int hp;
public void damage(int damage) { hp -= damage; }
}
class Boss
{
int hp;
public void damage(int damage) { hp -= damage; }
}
class Player
{
public void attackEnemy(Enemy enemy) { enemy.damage( 10 ); }
public void attackBoss (Boss boss) { boss.damage( 10 ); }
}
Code
class GameManager
{
Player player;
Enemy enemy;
Boss boss;
public void start() // ゲーム開始時に一度だけ呼ばれる
{
player = new Player();
enemy = new Enemy();
boss = new Boss();
}
	 	 public	 void	 update()

{
if (KeyDown( A_BUTTON )) // Aボタンが押されていたら
player.attackEnemy( enemy );
if (KeyDown( B_BUTTON )) // Aボタンが押されていたら
player.attackBoss( boss );
}
}
クラス図
Player は Enemy と Boss に依存してる
依存の影響
Open-Closed Principle
オープン・クローズドの原則
敵を増やそう
マジシャン、狂熊、ワルガキ
凶悪でかっこいいモンスターのアイデアがじゃぶじゃぶ湧き出る…!!
Code
class Player
{
public void attackEnemy(Enemy enemy)
{
enemy.damage( 10 );
}
public void attackBoss(Boss boss)
{
boss.damage( 10 );
}
public void attackMagician(Magician magician)
{
magician.damage( 10 );
}
public void attackWarBear(WarBear warBear)
{
warBear.damage( 10 );
}
public void attackBadBoy(BadBoy badBoy)
{
badBoy.damage( 10 );
}
}
クラス図
Player はいろんな敵を

知っている状態じゃないと成立しない
依存を減らしたい
• Playerの他者への依存は膨らむばかり
• 依存をなんとか減らせないか
共通のインターフェイス
• クラスの持つべき性質をルール化する
• 基底クラス
• C# の interface, C++なら多重継承
• Duck Typing
• ルールを決める手段は言語や処理系によって様々
• ルール:ダメージを受けることができる
damage()
Interface
// ルールの規定
interface	 ILife

{
function damage(int value);
}
// ルールに基づく実装
class	 Enemy	 implements	 ILife

{
var hp = 10;
	 	 public	 function	 damage(int	 value)

{
hp -= value;
}
}
Playerはシンプルに
class Player
{
// ILife インターフェイスを持つ相手ならだれでも
public void attack(ILife target)
{
target.damage( 10 ); // damage()を与えちゃうよ
}
}
敵がいくら増えても
class Boss implements ILife
{
int hp = 100;
public void damage(int value) { hp -= value/2; }
}
class Magician implements ILife
{
int hp = 5;
public void damage(int value) { hp -= value; }
}
class BadBoy implements ILife
{
int hp = 99;
public void damage(int value) { hp -= value; }
}
Playerは影響を受けない
class Player
{
// ILife インターフェイスを持つ相手ならだれでも
public void attack(ILife target)
{
target.damage( 10 );
}
}
クラス図
インターフェイスを
知っていれば

具体的な相手は知ら
なくて良い
良くなったこと
• 意識することが減る
• 敵を作ったら damage っていう関数を
必ず作って、Playerにその敵専用の攻
撃メソッドを追加するの忘れないでね
• ILifeのインターフェイス実装しといて
良くなったこと
• コンパイル時間の低下
• 敵のロジック修正するたびにPlayerが
再コンパイルされる
• 変更した敵のファイルだけ再コンパイル
される
インターフェース
• チーム開発、大規模開発において重要な
考え方
• 技術仕様のコード化
• テストが書きやすくなる
OCP
• 拡張をしても、他のモジュールへ影響を与
えない
• 新しい敵を追加しても Player は影響を
受けない
• Player のロジックを変更しても敵は影響
を受けない
ちょっと寄り道
class GameManager
{
Player player;
Enemy enemy; // implements ILife
Boss boss; // implements ILife
public void start() // ゲーム開始時に一度だけ呼ばれる
{
player = new Player();
enemy = new Enemy();
boss = new Boss();
}
	 	 public	 void	 update()	 //	 毎フレーム呼ばれる

{
if (KeyDown( A_BUTTON )) // Aボタンが押されていたら
player.attack( enemy );
if (KeyDown( B_BUTTON )) // Bボタンが押されていたら
player.attack( boss );
}
}
こいつ何者?
• 役割の明確でないクラス名
• インスタンスの生成・ゲームロジック・
入力処理。なんでも屋。
• ゲームに出てくるクラスを全部知っている
つまり、すべてのクラスに依存している
• 世界を知るもの
依存注入とは
Dependency Injection
新仕様
プレイヤーは武器を装備できて

敵を攻撃できるんだよ
Code
class Weapon {
public int power() { return 10; } // 攻撃力
}
class Player {
public void attack( ILife enemy )
{
Weapon weapon = new Weapon();
enemy.damage(weapon.power);
}
}
新仕様
新しくて、かっこ良くて、強い武器が

思いついてしまうんだ…!
Interface
interface IWeapon {
int power() // 攻撃力
}
class SuperSword implements IWeapon {
public int power() { return 9999; } // 攻撃力
}
class BigGreatAxe implements IWeapon {
public int power() { return 100; } // 攻撃力
}
class HyperUltimateKnife

…
Player
class Player {
IWeapon weapon;
public void equip( int type )
{
switch(weaponType)
{
case 1: weapon = new SuperSword(); break;
case 2: weapon = new BigGreatAxe(); break;
case 3: weapon = new HyperUltimateKnife(); break;
}
}
public void attack( ILife enemy )
{
enemy.damage( weapon.power() );
}
}
クラス図
Playerがすべての武器に依存してるぞ…
依存を絶つ
Player に誰かが武器を

渡してあげる (Inject)
依存注入のパターン
class Player {
IWeapon equipedWeapon;
Player( IWeapon weapon )
{
equipedWeapon = weapon;
}
public void setWeapon( IWeapon weapon )
{
equipedWeapon = weapon;
}
public function attack( ILife enemy )
{
enemy.damage( equipedWeapon.power() );
}
/* こんな書き方も */
public void setWeaponAndAttack( ILife enemy, IWeapon weapon )
{
enemy.damage( weapon.power );
}
}
Constructor Injection
Player( IWeapon weapon )
{
equipedWeapon = weapon;
}
Setter Injection
public void setWeapon( IWeapon weapon )
{
equipedWeapon = weapon;
}
Interface Injection
public void setWeaponAndAttack( ILife enemy, IWeapon weapon )
{
enemy.damage( weapon.power );
}
クラス図
Player は インターフェイスのみに依存
また寄り道
class GameManager
{
Player player;
Enemy enemy;
Boss boss;
Weapon weapon;
public void start() // ゲーム開始時に一度だけ呼ばれる
{
weapon = new Weapon();
player = new Player( weapon ); // 依存の注入 Constructor Injection
enemy = new Enemy();
boss = new Boss();
}
	 	 public	 void	 update()

{
if (KeyDown( A_BUTTON )) // Aボタンが押されていたら
player.attack( enemy );
if (KeyDown( B_BUTTON )) // Bボタンが押されていたら
player.attack( boss );
}
}
何が起きているか
• Player はインターフェイスさえ知っていれば、
どんな武器でも使いこなせるし、どんな敵にも
攻撃できるようになった
• 敵をじゃぶじゃぶ追加できるようになった
• 武器をじゃぶじゃぶ追加できるようになった
• GameManagerという のクラスがすべての
武器とすべての敵に依存している
次回DIコンテナ
についてやります

Mais conteúdo relacionado

Destaque

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Dependency Injectionとは