{"id":1658,"date":"2023-04-22T23:11:09","date_gmt":"2023-04-22T16:11:09","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=1658"},"modified":"2023-04-22T23:14:49","modified_gmt":"2023-04-22T16:14:49","slug":"csharp-flyweight-pattern","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-flyweight-pattern\/","title":{"rendered":"C# Flyweight Design Pattern"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to use the C# flyweight pattern to reduce memory usage by sharing data across similar objects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# Flyweight pattern<\/h2>\n\n\n\n<p>The Flyweight pattern is a structural design pattern that aims to reduce memory usage by sharing data across similar objects.<\/p>\n\n\n\n<p>In this pattern, you create a set of lightweight objects to represent common data shared across multiple objects. These lightweight objects are also called flyweights, which contain only the data that is unique to each object.<\/p>\n\n\n\n<p>In practice, you use the Flyweight pattern when you have to create a large number of objects, but each object has only a small amount of unique data. By using the Flyweight pattern, you can reduce the memory usage of the application significantly.<\/p>\n\n\n\n<p>One practical example of using the Flyweight pattern is in a rich text editor application where you need to manage a large number of character objects that represent the text. In this application, each character object has font, size, and color, which are the same for all characters of the same style.<\/p>\n\n\n\n<p>To manage flyweights, you can create a pool of flyweights to represent the common data (font, size, and color) shared among many characters. Each character object then contains a reference to the corresponding flyweight object, rather than duplicating the same data.<\/p>\n\n\n\n<p>For example, imagine that you want to create a document that contains a lot of text with different font styles, sizes, and colors. Instead of creating a new object for each character, you can create a flyweight object for each style and size combination, and then assign a reference to that flyweight object to each character object that shares that style and size combination.<\/p>\n\n\n\n<p>By doing this, you can reduce the memory usage of the rich text application significantly. Because the application doesn&#8217;t create many duplicate objects for the same style and size combinations. <\/p>\n\n\n\n<p>On top of that, the flyweight pattern can improve the performance of the application because it may reduce the time for creating and initializing many objects.<\/p>\n\n\n\n<p>This UML diagram illustrates how the flyweight pattern:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/csharptutorial.net\/wp-content\/uploads\/2023\/04\/CSharp-Flyweight-pattern.svg\" alt=\"c # Flyweight pattern\" class=\"wp-image-1660\"\/><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\">C# Flyweight pattern example<\/h2>\n\n\n\n<p>The following program demonstrates how to implement the Flyweight design pattern in C#:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">FlyweightPattern<\/span>;\n\n<span class=\"hljs-comment\">\/\/ Flyweight interface<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">interface<\/span> <span class=\"hljs-title\">ICharacter<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Display<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>;\n}\n\n<span class=\"hljs-comment\">\/\/ Concrete flyweight class<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Character<\/span> : <span class=\"hljs-title\">ICharacter<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">char<\/span> _symbol;\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">int<\/span> _size;\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">string<\/span> _font;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Character<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">char<\/span> symbol, <span class=\"hljs-keyword\">int<\/span> size, <span class=\"hljs-keyword\">string<\/span> font<\/span>)<\/span>\n    {\n        _symbol = symbol;\n        _size = size;\n        _font = font;\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Display<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        Console.WriteLine(<span class=\"hljs-string\">$\"Symbol: <span class=\"hljs-subst\">{_symbol}<\/span>, Size: <span class=\"hljs-subst\">{_size}<\/span>, Font: <span class=\"hljs-subst\">{_font}<\/span>\"<\/span>);\n    }\n}\n\n<span class=\"hljs-comment\">\/\/ Flyweight factory class<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">CharacterFactory<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> Dictionary&lt;<span class=\"hljs-keyword\">string<\/span>, ICharacter&gt; _characters = <span class=\"hljs-keyword\">new<\/span>();\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> ICharacter <span class=\"hljs-title\">GetCharacter<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">char<\/span> symbol, <span class=\"hljs-keyword\">int<\/span> size, <span class=\"hljs-keyword\">string<\/span> font<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> key = symbol.ToString() + size.ToString() + font;\n\n        <span class=\"hljs-keyword\">if<\/span> (!_characters.ContainsKey(key))\n        {\n            _characters.Add(key, <span class=\"hljs-keyword\">new<\/span> Character(symbol, size, font));\n        }\n\n        <span class=\"hljs-keyword\">return<\/span> _characters&#91;key];\n    }\n}\n\n<span class=\"hljs-comment\">\/\/ Client code<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Client<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>&#91;] args<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> factory = <span class=\"hljs-keyword\">new<\/span> CharacterFactory();\n\n        <span class=\"hljs-keyword\">var<\/span> char1 = factory.GetCharacter(<span class=\"hljs-string\">'A'<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-string\">\"Arial\"<\/span>);\n        char1.Display();\n\n        <span class=\"hljs-keyword\">var<\/span> char2 = factory.GetCharacter(<span class=\"hljs-string\">'B'<\/span>, <span class=\"hljs-number\">14<\/span>, <span class=\"hljs-string\">\"Times New Roman\"<\/span>);\n        char2.Display();\n\n        <span class=\"hljs-keyword\">var<\/span> char3 = factory.GetCharacter(<span class=\"hljs-string\">'A'<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-string\">\"Arial\"<\/span>);\n        char3.Display();\n\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define the <code>ICharacter<\/code> interface that has a method Display() that shows a character to the console: <\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">interface<\/span> <span class=\"hljs-title\">ICharacter<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Display<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, define the <code>Character<\/code> class that implements the <code>ICharacter<\/code> interface:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Character<\/span> : <span class=\"hljs-title\">ICharacter<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">char<\/span> _symbol;\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">int<\/span> _size;\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">string<\/span> _font;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Character<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">char<\/span> symbol, <span class=\"hljs-keyword\">int<\/span> size, <span class=\"hljs-keyword\">string<\/span> font<\/span>)<\/span>\n    {\n        _symbol = symbol;\n        _size = size;\n        _font = font;\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Display<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        Console.WriteLine(<span class=\"hljs-string\">$\"Symbol: <span class=\"hljs-subst\">{_symbol}<\/span>, Size: <span class=\"hljs-subst\">{_size}<\/span>, Font: <span class=\"hljs-subst\">{_font}<\/span>\"<\/span>);\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>Character<\/code> class has three properties symbol, size, and font. It also implements the <code>Display()<\/code> method that shows these properties to the console.<\/p>\n\n\n\n<p>Third, define the <code>CharacterFactory<\/code> class that is responsible for managing the creation and sharing of flyweight objects:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">CharacterFactory<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> Dictionary&lt;<span class=\"hljs-keyword\">string<\/span>, ICharacter&gt; _characters = <span class=\"hljs-keyword\">new<\/span>();\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> ICharacter <span class=\"hljs-title\">GetCharacter<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">char<\/span> symbol, <span class=\"hljs-keyword\">int<\/span> size, <span class=\"hljs-keyword\">string<\/span> font<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> key = symbol.ToString() + size.ToString() + font;\n\n        <span class=\"hljs-keyword\">if<\/span> (!_characters.ContainsKey(key))\n        {\n            _characters.Add(key, <span class=\"hljs-keyword\">new<\/span> Character(symbol, size, font));\n        }\n\n        <span class=\"hljs-keyword\">return<\/span> _characters&#91;key];\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, define the <code>Client<\/code> class that uses the <code>CharacterFactory<\/code> to obtain flyweight objects for different characters with different sizes and fonts:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">public <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Client<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> Main(string&#91;] args)\r\n    {\r\n        <span class=\"hljs-keyword\">var<\/span> factory = <span class=\"hljs-keyword\">new<\/span> CharacterFactory();\r\n\r\n        <span class=\"hljs-keyword\">var<\/span> char1 = factory.GetCharacter(<span class=\"hljs-string\">'A'<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-string\">\"Arial\"<\/span>);\r\n        char1.Display();\r\n\r\n        <span class=\"hljs-keyword\">var<\/span> char2 = factory.GetCharacter(<span class=\"hljs-string\">'B'<\/span>, <span class=\"hljs-number\">14<\/span>, <span class=\"hljs-string\">\"Times New Roman\"<\/span>);\r\n        char2.Display();\r\n\r\n        <span class=\"hljs-comment\">\/\/ use the flyweight instead of creating new object<\/span>\r\n        <span class=\"hljs-keyword\">var<\/span> char3 = factory.GetCharacter(<span class=\"hljs-string\">'A'<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-string\">\"Arial\"<\/span>); \r\n        char3.Display();\r\n\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Notice that when you request a flyweight object, the <code><code><code>CharacterFactory<\/code><\/code><\/code> first checks if an object with the same key (symbol, size, and font) already exists in its internal dictionary.<\/p>\n\n\n\n<p>If the object does not exist, the <code><code><code>CharacterFactory<\/code><\/code><\/code> creates a new <code>Character<\/code> object and adds it to the dictionary. Otherwise, <code><code><code>CharacterFactory<\/code><\/code><\/code> returns the existing object.<\/p>\n\n\n\n<p>When you run the program, you should see the output displaying the symbol, size, and font of each character object. <\/p>\n\n\n\n<p>Because the third character object is a duplicate of the first one, the <code>CharacterFactory<\/code> returns the existing object instead of creating a new one.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the C# flyweight pattern to reduce memory usage by sharing data across similar objects.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1658\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-flyweight-pattern\/\"\n\t\t\t\tdata-post-title=\"C# Flyweight Design Pattern\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1658\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-flyweight-pattern\/\"\n\t\t\t\tdata-post-title=\"C# Flyweight Design Pattern\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you will learn how to use the C# flyweight pattern to reduce memory usage by sharing data across similar objects. Introduction to the C# Flyweight pattern The Flyweight pattern is a structural design pattern that aims to reduce memory usage by sharing data across similar objects. In this pattern, you create [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1441,"menu_order":18,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1658","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1658","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=1658"}],"version-history":[{"count":4,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1658\/revisions"}],"predecessor-version":[{"id":1664,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1658\/revisions\/1664"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1441"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=1658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}