教務(wù)處網(wǎng)站建設(shè)西安seo推廣
Unity實現(xiàn)設(shè)計模式——適配器模式
適配器模式又稱為變壓器模式、包裝模式(Wrapper) 將一個類的接口變換成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠在一起工作。
在一個在役的項目期望在原有接口的基礎(chǔ)上拓展,那么適配器模式是最適合的。 即需要使用一個已有或新建的類,但這個類又不符合系統(tǒng)的接口,則可以使用適配器模式。
client:需要使用適配器的對象,不需要關(guān)心適配器內(nèi)部的實現(xiàn),只對接目標角色。
Target:目標角色,和client直接對接,定義了client需要用到的功能。
Adaptee:需要被進行適配的對象。
Adapter:適配器,負責將源對象轉(zhuǎn)化,給client做適配。
下面還是使用兩個例子來說明適配器模式
(一)使用比較抽象的例子來說明
1.Target
class Target
{public virtual void Request(){Debug.Log("Called Target Request()");}
}
2.Adaptee
class Adaptee
{public void SpecificRequest(){Debug.Log("Called SpecificRequest()");}
}
可以看到目標對象和待適配對象并不匹配
使用適配器來讓二者聯(lián)系起來
3.Adapter
class Adapter : Target
{private Adaptee _adaptee = new Adaptee();public override void Request(){// Possibly do some other work// and then call SpecificRequest_adaptee.SpecificRequest();}
}
4.測試
public class AdapterStructure : MonoBehaviour
{void Start( ){// Create adapter and place a requestTarget target = new Adapter();target.Request();}
}
可以發(fā)現(xiàn)兩個無關(guān)的類很自然的就聯(lián)系起來了!
(二)使用具體的例子來說明
現(xiàn)在有敵方攻擊者的基類,派生出了敵方坦克,同時有敵方機器人但是機器人的接口和敵方攻擊者的接口不同,我們需要進行適配
1. IEnemyAttacker
public interface IEnemyAttacker{void FireWeapon();void DriveForward();void AssignDriver(string driver);}
2. EnemyTank
public class EnemyTank : IEnemyAttacker{public void FireWeapon(){int attackDamage = Random.Range(1, 10);Debug.Log("Enemy Tank does " + attackDamage + " damage");}public void DriveForward(){int movement = Random.Range(1, 5);Debug.Log("Enemy Tank moves " + movement + " spaces");}public void AssignDriver(string driver){Debug.Log(driver + " is driving the tank");}}
3. EnemyRobot
public class EnemyRobot{public void SmashWithHands(){int attackDamage = Random.Range(1, 10);Debug.Log("Robot causes " + attackDamage + " damage with it hands");}public void WalkForward(){int movement = Random.Range(1, 3);Debug.Log("Robot walks " + movement + " spaces");}public void ReactToHuman(string driverName){Debug.Log("Robot tramps on " + driverName);}}
可以看出這里不同,當然可以對EnemyRobot派生自IEnemyAttacker接口,然后重新實現(xiàn)接口,但是在多人協(xié)作的場景,這樣是不允許的。同時該類可能在別處引用,顯然有很大的工作量要修改。
4. EnemyRobotAdaper
public class EnemyRobotAdaper : IEnemyAttacker{EnemyRobot robot;public EnemyRobotAdaper(EnemyRobot robot){this.robot = robot;}public void FireWeapon(){robot.SmashWithHands();}public void DriveForward(){robot.WalkForward();}public void AssignDriver(string driver){robot.ReactToHuman(driver);}}
5.測試
public class AdapterPatternExample2 : MonoBehaviour{void Start(){IEnemyAttacker tank = new EnemyTank();EnemyRobot fredTheRobot = new EnemyRobot();IEnemyAttacker adapter = new EnemyRobotAdaper(fredTheRobot);fredTheRobot.ReactToHuman("Hans");fredTheRobot.WalkForward();tank.AssignDriver("Frank");tank.DriveForward();tank.FireWeapon();adapter.AssignDriver("Mark");adapter.DriveForward();adapter.FireWeapon();}}