Encapsulation
Another option is to use encapsulation. The base class decides whether an item can be bought, depending on whether the item has an owner. We do assert here that an item can have at most 1 owner.
public abstract class Item
{
public Person Owner { get; private set; }
public bool IsBought => Owner != null;
protected abstract bool OnBuy(Person buyer);
public bool Buy(Person buyer)
{
if (IsBought)
{
Console.WriteLine("The item already has an owner");
return false;
}
var wasBought = OnBuy(buyer);
if (wasBought)
{
Owner = buyer;
}
return wasBought;
}
}
Derived classes are not allowed to bypass the policy that an item which has already been bought can be bought again, but they can add additional checks whether the item could be bought. For instance, a child cannot buy a sword.
public class Sword : Item
{
protected override bool OnBuy(Person buyer)
{
if (buyer.IsChild)
{
Console.WriteLine("A child cannot buy a sword");
return false;
}
Console.WriteLine($"{buyer.Name} bought a sword");
return true;
}
}
The Person
class used in this example:
public class Person
{
public string Name;
public bool IsChild;
}
C#
andUnityScript
. Are you sure you need an answer which explains how to do this in the old, deprecated UnityScript scripting language? If you only need a solution for writing Unity scripts in C#, please don't use that tag. \$\endgroup\$