CSharp · Console
using System;
using System.Collections.ObjectModel;
public class InventoryItem
{
public string Name { get; set; }
}
public class SuperInventoryItem : InventoryItem { }
public abstract class InventoryItemAbstractFactory<T> where T : InventoryItem
{
public abstract T Create();
}
public class InventoryItemFactory : InventoryItemAbstractFactory<InventoryItem>
{
public override InventoryItem Create() => new InventoryItem();
}
public class SuperInventoryItemFactory : InventoryItemAbstractFactory<SuperInventoryItem>
{
public override SuperInventoryItem Create() => new SuperInventoryItem();
}
public class Inventory<T> where T : InventoryItem
{
private readonly ObservableCollection<T> _inventory = new ObservableCollection<T>();
private readonly InventoryItemAbstractFactory<T> _factory;
public Inventory(InventoryItemAbstractFactory<T> factory) => _factory = factory;
public void Add() => _inventory.Add(_factory.Create());
public int Count => _inventory.Count;
}
public class Program
{
public static void Main()
{
var c1 = new Inventory<InventoryItem>(new InventoryItemFactory());
c1.Add();
c1.Add();
var c2 = new Inventory<SuperInventoryItem>(new SuperInventoryItemFactory());
c2.Add();
c2.Add();
Console.WriteLine(c1.Count);
Console.WriteLine(c2.Count);
}
}