Consider this following code:
public interface IStackable {
Item GetItem();
int GetAmount();
}
// I have an Item data
public class Item {
private string _name;
}
// composite pattern: adding amount to item data
public class StackableItem : IStackable {
private Item _item;
private int _amount;
public Item GetItem() {
return _item;
}
public int GetAmount() {
return _amount;
}
// How to make this conform to interface?
public void AddAmount(int amount) {
this._amount += amount;
}
public void AddItem(IStackable stackable) {
this._amount += stackable.GetAmount();
}
//*see comment: public void AddItem(StackableItem item) {}
}
// composite pattern: adding amount to item data
public class UniqueItem : IStackable {
private List<Item> _items;
public Item GetItem() {
return _items.First();
}
public int GetAmount() {
return _items.Count;
}
// How to make this conform to interface?
public void AddItem(Item item) {
_items.Add(item);
}
public void AddItem(IStackable stackable) {
_items.Add() // how am I supposed to resolve this?
// pseudo code:
// for every item in stackable (but it has to be uniqueitem),
// add every item from stackable to this object;
// then I need to destroy that stackable object
}
//*see comment: public void AddItem(UniqueItem item) {}
}
I think it would be bad to add AddItem(IStackable stackable) to the interface. Even if I did, I can't make method that works as intended.
The only way I can think is to cast Stackable to Unique Items first, but I believe that's not a good way also.
*I think the best way is to add a method with different signature conforms to interface, So How to add method with different signature, but known type, conforms to interface?
Edit: StackableItem example: Potion x10
UniqueItem example: 3 gun with each have different ammo
IStackable is for the UI, so that UI don't need to know their implementation and still can show the Item and Amount accordingly, (and neatly become one IStackable)
Aucun commentaire:
Enregistrer un commentaire