Skip to content

Instantly share code, notes, and snippets.

@asarnaout
Last active October 3, 2018 14:47
Show Gist options
  • Save asarnaout/44e70ca33111e43f915932ef9f94cbe7 to your computer and use it in GitHub Desktop.
Save asarnaout/44e70ca33111e43f915932ef9f94cbe7 to your computer and use it in GitHub Desktop.
Flyweight Pattern Gist
public class Zone : IEquatable<Zone>
//An immutable flyweight...This represents a domain value object
{
public string ZipCode { get; }
public IReadOnlyCollection<string> AvailableCouriers { get; private set; }
public Zone(string zipCode)
{
ZipCode = zipCode;
AvailableCouriers = new List<string>();
}
public Zone(string zipCode, IEnumerable<string> couriers) : this(zipCode)
{
AvailableCouriers = new List<string>(couriers.Distinct());
}
public Zone RegisterCourier(string courier)
{
var newCouriers = new List<string>(AvailableCouriers)
{
courier
};
return new Zone(ZipCode, newCouriers);
}
public bool Equals(Zone other)
{
if (other == default(Zone))
return false;
if (ReferenceEquals(this, other))
return true;
if (!string.Equals(ZipCode, other.ZipCode, StringComparison.OrdinalIgnoreCase))
return false;
if (AvailableCouriers.Count != other.AvailableCouriers.Count)
return false;
if (!AvailableCouriers.All(x => other.AvailableCouriers.Contains(x)))
return false;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment