背景
接到上面一個需求,要設(shè)計一個英雄打怪圃酵,怎么做呢雏门?
設(shè)計
簡要的設(shè)計圖
我們可以看到Role通過依賴注入武器嘿歌,這樣子,我們就可以隨時替換攻擊策略了茁影。
客戶端代碼
在客戶端使用宙帝,我們先給出沒有使用容器的方式:
public function test_use_sword()
{
//生成怪物
$monster1 = new Monster( "小怪A", 50 );
$monster2 = new Monster( "小怪B", 50 );
$monster3 = new Monster( "關(guān)主", 200 );
$monster4 = new Monster( "最終Boss", 1000 );
//生成角色
$role = new Role("超級英雄");
//木劍攻擊
$role->setWeapon(new WoodSword());
$role->attack($monster1);
//鐵劍攻擊
$role->setWeapon(new IronSword());
$role->attack($monster2);
$role->attack($monster3);
//魔劍攻擊
$role->setWeapon(new MagicSword());
$role->attack($monster3);
$role->attack($monster4);
$role->attack($monster4);
$role->attack($monster4);
}
再給出使用容器的方式:
public function test_user_container()
{
$container = new Container();
$container->bind('GameDemo\IAttackStrategy','GameDemo\WoodSword');
//生成怪物
$monster1 = new Monster( "小怪A", 50 );
$monster2 = new Monster( "小怪B", 50 );
$monster3 = new Monster( "關(guān)主", 200 );
$monster4 = new Monster( "最終Boss", 1000 );
//生成角色
/**
* @var Role
*/
$role = $container->make('GameDemo\Role',['英雄']);
$container->rebinding('GameDemo\IAttackStrategy',function($c, $weapon) use($role){
$role->setWeapon($weapon);
});
//木劍攻擊
$role->attack($monster1);
//鐵劍攻擊
$container->bind('GameDemo\IAttackStrategy','GameDemo\IronSword');
$role->attack($monster2);
$role->attack($monster3);
//魔劍攻擊
$container->bind('GameDemo\IAttackStrategy','GameDemo\MagicSword');
$role->attack($monster3);
$role->attack($monster4);
$role->attack($monster4);
$role->attack($monster4);
}
對比后,可以發(fā)現(xiàn)募闲,使用容器后步脓,客戶端不用自己去實例化武器了,全都交給容器去做浩螺,極大的簡化了客戶端靴患。