2016-11-08 116 views
0

有人能證實我下面的做法是對還是有更好的選擇:泛型類型的使用

// An interface 
IAnimal 
{ 
    pubilc void Hunt(); 
} 

// An abstract class 
Animal<T> : IAnimal 
{ 
    public void Hunt() 
    { 
     UseWeapon(T); 
    } 

    protected abstract T GetWeapon(); 
    protected abstract void UseWeapon(T weapon); 
} 

,這樣我可以有這樣實現:

Tiger : Animal<Claw> 
Hyena : Animal<Teeth> 
Eagle : Animal<Beak> 

對於如:

Tiger : Animal<Claw> 
{ 
    protected override void UseWeapon(Claw claw) 
    { 
     // logic here 
    } 

    protected override void GetWeapon() 
    { 
     // logic here to populate props & return Claw(); 
    } 
} 

然後我可以打電話:

如果您需要多種武器

interface IAnimal 
{ 
    pubilc void Hunt(); 
} 

interface IWeapon 
{ 
} 

Animal : IAnimal 
{ 
    IWeapon _weapon; 

    public void Animal(IWeapon weapon) 
    { 
     _weapon = weapon; 
    } 

    public void Hunt() 
    { 
     UseWeapon(_weapon); 
    } 

    protected abstract void UseWeapon(IWeapon weapon); 
} 

,那麼你只需要注入在構造函數中IEnumerable<IWeapon>,並相應地更改邏輯:

IAnimal animal = GetRandomAnimal(); // OR GetTiger(); 
animal.Hunt() 
+3

如果你不得不實施'使用'Claws'和'Teeth'作爲武器的Bear'? –

+1

此代碼不起作用。 'public void Hunt(){UseWeapon(T); }' –

+0

是的,我同意@DmitryBychenko,它似乎限制每個動物的可用選項,而不是 – Icepickle

回答

1

我寧願用這個辦法,與DI工作很容易。