这是一系列的设计模式。本书所有案例均来自《Head-FirstDesignPattern(中文版)》,Github地址,欢迎大家围观,starstrategyPattern定义了算法族,单独封装,让它们可以互相调用,这种模式使得算法的改变独立于调用算法的客户端。设计一个具有多个可以使用不同武器的游戏角色的冒险游戏。游戏中的角色可以自由切换武器,每个角色一次只能使用一把武器。类图设计如下:抽象武器行为接口interfaceWeaponBehavior{/***设置使用什么样的武器**/publicfunctionuseWeapon();}武器类KnifeBehavior具体实现类实现WeaponBehavior{publicfunctionuseWeapon(){//使用刀return1;}}classSwordBehaviorimplementsWeaponBehavior{publicfunctionuseWeapon(){//使用大保健return1024;}}//...各种游戏角色继承自Character超类。抽象公共类角色{protected$weapon;公共功能setWeapon(WeaponBehavior$weapon){$this->weapon=$weapon;}/***获取角色战斗力*/publicfunctionfightPower(){return$this->weapon->useWeapon()}}角色具体实现.classKingextendsCharacter{publicfunction__construct(){//国王使用斧头$this->setWeapon(newSwordBehavior);}}classQueenextendsCharacter{publicfunction__construct(){//女王使用匕首$this->setWeapon(newKnifeBehavior);}}等等...我们的设计原则是接口编程,但是我们还是在角色的构造函数中创建了具体的武器行为类。因为这是我们的第一个设计模式,所以我们稍后会用其他模式来纠正这个问题。战斗(新王)->fightPower();//1024;(新皇后)->fightPower();//1;
