2016-11-08 109 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工作很容易。