Exemple #1
0
        public void Operation(FlyweightCar uniqueState)
        {
            string s = JsonConvert.SerializeObject(this._sharedState);
            string u = JsonConvert.SerializeObject(uniqueState);

            System.Console.WriteLine($"Flyweight: Displaying shared {s} and unique {u} state.");
        }
Exemple #2
0
        public static void addCarToPoliceDatabase(FlyweightFactory factory, FlyweightCar car)
        {
            Console.WriteLine("\nClient: Adding a car to database.");

            var flyweight = factory.GetFlyweight(new FlyweightCar {
                Color   = car.Color,
                Model   = car.Model,
                Company = car.Company
            });

            // The client code either stores or calculates extrinsic state and
            // passes it to the flyweight's methods.
            flyweight.Operation(car);
        }
Exemple #3
0
        // Returns an existing Flyweight with a given state or creates a new
        // one.
        public Flyweight GetFlyweight(FlyweightCar sharedState)
        {
            string key = this.getKey(sharedState);

            if (flyweights.Where(t => t.Item2 == key).Count() == 0)
            {
                System.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);
        }
Exemple #4
0
        private string getKey(FlyweightCar key)
        {
            List <string> elements = new List <string>();

            elements.Add(key.Model);
            elements.Add(key.Color);
            elements.Add(key.Company);

            if (key.Owner != null && key.Number != null)
            {
                elements.Add(key.Number);
                elements.Add(key.Owner);
            }

            elements.Sort();

            return(string.Join("_", elements));
        }
Exemple #5
0
 public Flyweight(FlyweightCar car)
 {
     this._sharedState = car;
 }