|
|
|
|
using Flyweight.Objects;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Flyweight.Flyweights
|
|
|
|
|
{
|
|
|
|
|
internal class FlyweightFactory
|
|
|
|
|
{
|
|
|
|
|
private List<Tuple<Flyweight, string>> _flyweights = new List<Tuple<Flyweight, string>>();
|
|
|
|
|
|
|
|
|
|
public FlyweightFactory(params Car[] args)
|
|
|
|
|
{
|
|
|
|
|
foreach (var elem in args)
|
|
|
|
|
{
|
|
|
|
|
_flyweights.Add(new Tuple<Flyweight, string>(new Flyweight(elem), GetKey(elem)));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string GetKey(Car car)
|
|
|
|
|
{
|
|
|
|
|
List<string> elements = new List<string>();
|
|
|
|
|
|
|
|
|
|
elements.Add(car.Model);
|
|
|
|
|
elements.Add(car.Color);
|
|
|
|
|
elements.Add(car.Company);
|
|
|
|
|
|
|
|
|
|
if (car.Owner != null && car.Number != null)
|
|
|
|
|
{
|
|
|
|
|
elements.Add(car.Number);
|
|
|
|
|
elements.Add(car.Owner);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
elements.Sort();
|
|
|
|
|
|
|
|
|
|
return String.Join("_", elements);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Flyweight GetFlyweight(Car sharedState)
|
|
|
|
|
{
|
|
|
|
|
string key = GetKey(sharedState);
|
|
|
|
|
if (_flyweights.Where(t => t.Item2 == key).Count() == 0)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine("FlyweightFactory: Can't find a flyweight, creating new one.");
|
|
|
|
|
_flyweights.Add(new Tuple<Flyweight, string>(new Flyweight(sharedState), key));
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine("FlyweightFactory: Reusing existing flyweight.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return _flyweights.Where(t => t.Item2 == key).FirstOrDefault().Item1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void ListFlyweights()
|
|
|
|
|
{
|
|
|
|
|
int count = _flyweights.Count;
|
|
|
|
|
Console.WriteLine($"FlyweightFactory: I have {count} flyweights");
|
|
|
|
|
foreach (var flyweight in _flyweights)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine(flyweight.Item2);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|