背景
需求描述接到上面一个需求,要设计一个英雄打怪,怎么做呢?
设计
简要的设计图
设计图我们可以看到Role通过依赖注入武器,这样子,我们就可以随时替换攻击策略了。
客户端代码
在客户端使用,我们先给出没有使用容器的方式:
public function test_use_sword()
{
//生成怪物
$monster1 = new Monster( "小怪A", 50 );
$monster2 = new Monster( "小怪B", 50 );
$monster3 = new Monster( "关主", 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( "关主", 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);
}
对比后,可以发现,使用容器后,客户端不用自己去实例化武器了,全都交给容器去做,极大的简化了客户端。
网友评论