How to Use the Flyweight Design Template in C #

0

Design patterns help us solve design problems often encountered in software development and reduce the complexity of our code. Gang of Four design patterns fall into three categories: creative, structural, and behavioral.

The Flyweight design model belongs to the structural category. The Flyweight pattern helps reduce memory consumption when working with many similar objects at the same time. This article examines how we can work with the Flyweight design template in C #.

To work with the code samples provided in this article, you must have Visual Studio 2019 installed on your system. If you do not already have a copy, you can download Visual Studio 2019 here.

Create a Console Application Project in Visual Studio

First, let’s create a .NET Core Console app project in Visual Studio. Assuming you have Visual Studio 2019 installed on your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create a new project”.
  3. In the “Create a new project” window, select “Console application (.NET Core)” from the list of displayed templates.
  4. Click on Next.
  5. In the “Configure your new project” window, specify the name and location of the new project.
  6. Click on Create.

You should now have a new .NET Core Console Application project ready to use in Visual Studio 2019. We will use this project in the following sections of this article.

The Flyweight design template and its use

The Flyweight design pattern reduces the amount of memory required to create a number of large objects of the same type in an application. The flyweight is an object that reduces memory pressure by sharing data with similar objects. Thus, a new object is only created when needed, that is, if no corresponding object is available. By reducing memory consumption, the Flyweight pattern improves performance.

A typical use case of the Flyweight pattern is when you need to create large objects of the same type. The Description of the band of four: “Use sharing to efficiently support a large number of fine-grained objects. “

A flyweight object can have one of the following states:

  • Intrinsic state – data is independent of state and is typically stored in the flyweight object and can be shared
  • Extrinsic state – data is state dependent and therefore cannot be shared

The participants in the Flyweight design model are:

  • Flyweight – this is usually an interface for flyweight objects
  • ConcreteFlyweight – this is a class that implements the Flyweight interface
  • FlyweightFactory – this is a factory class used to create concrete objects of type ConcreteFlyweight
  • Client – this stores references to flyweight instances

Implement the abstract class and the Flyweight method in C #

To implement the Flyweight design pattern in C #, let’s start by defining the abstract base class named Flyweight. This class will contain the declaration of an abstract method named Display. The following code snippet demonstrates the Flyweight abstract class.

public abstract class Flyweight
 {
     public abstract void Display();
 }

The ConcreteFlyweight class extends the Flyweight class and implements the abstract method. The following code list shows the ConcreteFlyweight class.

public class ConcreteFlyweight : Flyweight
    {
        private readonly string _key = null;
        public ConcreteFlyweight(string key)
        {
            _key = key;
        }
        public override void Display()
        {
            Console.WriteLine("The Key is: "+ _key);
        }
    }

Implement the FlyweightFactory class in C #

The FlyweightFactory class creates and stores flyweight instances in a Dictionary instance. This class contains the GetFlyweight () method which returns a ConcreteFlyweight instance based on a given key. If the instance is present in the Dictionary, it is returned, otherwise a new instance of ConcreteFlyweight is created and returned. The following code list illustrates the FlyweightFactory class.

public class FlyweightFactory
    {
        private Dictionary flyweights = new
        Dictionary();
        public Flyweight GetFlyweight(string key)
        {
            Flyweight flyweight = null;
            if (flyweights.ContainsKey(key))
            {
                flyweight = flyweights[key];
            }
            else
            {
                flyweight = new ConcreteFlyweight(key);
                flyweights.Add(key, flyweight);
            }
            return flyweight;
        }
    }

Note that in this example, we are using a ConcreteFlyweight class. Several instances of this class differ from each other on the value of the key. In practice, you might want to create several concrete classes that extend the Flyweight class. We have omitted several instances here for simplicity.

Implement the Flyweight client in C #

Finally, this is what the client would look like.

static void Main(string[] args)
{
  var factory = new FlyweightFactory();
  var flyweight = factory.GetFlyweight("A");
  flyweight.Display();
  Console.Read();
}

Flyweight design template example in C #

Here is the full program for your reference.

public abstract class Flyweight
    {
        public abstract void Display();
    }
    public class ConcreteFlyweight : Flyweight
    {
        private readonly string _key = null;
        public ConcreteFlyweight(string key)
        {
            _key = key;
        }
        public override void Display()
        {
            Console.WriteLine("The Key is: "+ _key);
        }
    }
    public class FlyweightFactory
    {
        private Dictionary flyweights = new
        Dictionary();
        public Flyweight GetFlyweight(string key)
        {
            Flyweight flyweight = null;
            if (flyweights.ContainsKey(key))
            {
                flyweight = flyweights[key];
            }
            else
            {
                flyweight = new ConcreteFlyweight(key);
                flyweights.Add(key, flyweight);
            }
            return flyweight;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new FlyweightFactory();
            var flyweight = factory.GetFlyweight("A");
            flyweight.Display();
            Console.Read();
        }
    }

When you run the above program, you should see the following output.

flyweight design template c IDG

Figure 1: The Flyweight design template in action!

You can take advantage of the Flyweight design pattern in scenarios where memory availability is a constraint. However, in practice, the complexities involved in implementing the Flyweight design pattern often outweigh the benefits. Therefore, the usefulness of the Flyweight model is limited. In many cases, a better alternative is the Prototype design template.

Copyright © 2020 IDG Communications, Inc.


Source link

Share.

Leave A Reply