<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Federico Bruzzone on Medium]]></title>
        <description><![CDATA[Stories by Federico Bruzzone on Medium]]></description>
        <link>https://medium.com/@federico.bruzzone.i?source=rss-6ec37c982cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZIVo4GQdnbUbyEUs3LjX2g@2x.jpeg</url>
            <title>Stories by Federico Bruzzone on Medium</title>
            <link>https://medium.com/@federico.bruzzone.i?source=rss-6ec37c982cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:34:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@federico.bruzzone.i/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prototype — Class Creational]]></title>
            <link>https://blog.devgenius.io/prototype-class-creational-21045dccc0d9?source=rss-6ec37c982cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/21045dccc0d9</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Federico Bruzzone]]></dc:creator>
            <pubDate>Mon, 08 May 2023 00:00:09 GMT</pubDate>
            <atom:updated>2023-05-24T10:03:54.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prototype — Class Creational</h3><h4>A summary of GoF Design Patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Ihw0lhmmU0q4dkIw.png" /><figcaption>By <strong>Dmitry Zhart</strong> ( <a href="https://refactoring.guru/">refactoring.guru</a>)</figcaption></figure><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/prototype-object-creational/"><em>https://federicobruzzone.github.io</em></a><em> on May 8, 2023.</em></p><h3>Intent</h3><p>Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.</p><h3>Also Known As</h3><p>…</p><h3>Motivation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*saZts0lrGQWQ6xzY.png" /></figure><p>You could build an editor for music scores by customizing a general framework for graphical editors and adding new objects that represent notes, rests, and staves. The editor framework may have a palette of tools for adding these music objects to the score.</p><p>Let’s assume the framework provides an abstract Graphic class for graphical components, like notes and staves. Moreover, it’ll provide an abstract Tool class for defining tools like those in the palette. The framework also predefines a Graphic-Tool subclass for tools that create instances of graphical objects and add them to the document.</p><p>But GraphicTool presents a problem to the framework designer. The classes for notes and staves are specific to our application, but the GraphicTool class belongs to the framework. GraphicTool doesn’t know how to create instances of our music classes to add to the score.</p><p>The solution lies in making GraphicTool create a new Graphic by copying or “cloning” an instance of a Graphic subclass. We call this instance a <strong>prototype</strong>. GraphicTool is parameterized by the prototype it should clone and add to the document.</p><p>We can use the Prototype pattern to reduce the number of classes even further. We have separate classes for whole notes and half notes, but that’s probably unnecessary. Instead they could be instances of the same class initialized with different bitmaps and durations.</p><h3>Applicability</h3><p>Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; <em>and</em></p><ul><li>when the classes to instantiate are specified at run-time, for example, by dynamic loading; <em>or</em></li><li>to avoid building a class hierarchy offactories that parallels the class hierarchy of products; <em>or</em></li><li>when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.</li></ul><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YzFdEs38bSR-HyFk.png" /></figure><h3>Collaborations</h3><h4>Prototype</h4><p><em>(Graphic)</em></p><ul><li>declares an interface for cloning itself.</li></ul><h3>ConcretePrototype</h3><p><em>(Staff, WholeNote, HalfNote)</em></p><ul><li>implements an operation for cloning itself.</li></ul><h3>Client</h3><p><em>(GraphicTool)</em></p><ul><li>creates a new object by asking a prototype to clone itself.</li></ul><h3>Collaborations</h3><p>A client asks a prototype to clone itself.</p><h3>Consequences</h3><p>Prototype has many of the same consequences that Abstract Factory and Builder have: It hides the concrete product classes from the client. Moreover, these patterns let a client work with application-specific classes without modification.</p><p>Additional benefits of the Prototype pattern:</p><ol><li><em>Adding and removing products at run-time</em>: Prototypes let you incorporate a new concrete product class into a system simply by registering a prototypical instance with the client.</li><li><em>Specifying new objects by varying values</em>: Highly dynamic systems let you define new behavior through object composition by specifying values for an object’s variables. You effectively define new kinds of objects by instantiating existing classes andregistering the instances as prototypes of client objects. A client can exhibit new behavior by delegating responsibility to the prototype.</li><li><em>Specifying new objects by varying structure</em>: Many applications build objects from parts and subparts.</li><li><em>Reduced subclassing</em>: Factory Method often produces a hierarchy of Creator classes that parallels the product class hierarchy. The Prototype pattern lets you clone a prototype instead of asking a factory method to make a new object.</li><li><em>Configuring an application with classes dynamically</em>: Some run-time environments let you load classes into an application dynamically. An application that wants to create instances of a dynamically loaded class won’t be able to reference its constructor statically. Instead, the run-time environment creates an instance of each class automatically when it’s loaded, and it registers the instance with a prototype manager</li></ol><h3>Implementation</h3><p>Prototype is particularly useful with static languages like C++, where classes are not objects, and little or no type information is available at run-time.</p><p>Consider the following issues when implementing prototypes:</p><ol><li><em>Using a prototype manager</em>: When the number of prototypes in a system in not fixed, keep the registry of available prototypes. A prototype manager is an associative store that returns the prototype matching a given key.</li><li><em>Implementing the Clone operation</em>: The hardest part of the Prototype pattern is implementing the Clone operation correctly. Most languages provide some support for cloning objects, but using inheritance or copy-constructor don’t solve the “shallow copy versus deep copy” problem. A shallow copy is simple and often sufficient, but cloning prototypes with complex structures usually requires a deep copy. If objects in the system provide Save and Load operations, then you can use them to provide a default implementation of Clone.</li><li><em>Initializing clones</em>: You generally can’t pass these values in the Clone operation, because their number will vary between classes of prototypes. It might be the case that your prototype classes already define operations for (re)setting key pieces of state.</li></ol><h3>Sample Code</h3><p>To better understand the following code and the classes used look</p><p><a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode"><strong>here🔗!</strong></a></p><p>We’ll define a <em>MazePrototypeFactory</em> subclass of the <em>MazeFactory</em> class. MazePrototypeFactory will be initialized with prototypes of the objects it will create so that we don’t have to subclass it just to change the classes of walls or rooms it creates.</p><ul><li><em>MazePrototypeFactory</em> augments the <em>MazeFactory</em> interface with a constructor that takes the prototypes as arguments.</li><li>The new constructor simply initializes its prototypes.</li><li>The member functions for creating walls, rooms, and doors are similar: Each clones a prototype and then initializes it. Here are the definitions of <em>MakeWall</em> and <em>MakeDoor</em>:</li></ul><pre>import commoncode.*;<br><br>public class MazePrototypeFactory extends MazeFactory {<br>    <br>    private Maze _prototypeMaze = null;<br>    private Room _prototypeRoom = null;<br>    private Wall _prototypeWall = null;<br>    private Door _prototypeDoor = null;<br><br>    public MazePrototypeFactory(Maze m, Wall w, Room r, Door d) {<br>        this._prototypeMaze = m;<br>        this._prototypeWall = w;<br>        this._prototypeRoom = r;<br>        this._prototypeDoor = d;<br>    }<br><br>    @Override<br>    public Maze MakeMaze() {<br>        return _prototypeMaze.clone();<br>    }<br><br>    @Override<br>    public Wall MakeWall() {<br>        return _prototypeWall.clone();<br>    }<br><br>    @Override<br>    public Room MakeRoom(int n) {<br>        Room room = _prototypeRoom.clone();<br>        room.initializer(n);<br>        return room;<br>    }<br><br>    @Override<br>    public Door MakeDoor(Room r1, Room r2) {<br>        Door door =  _prototypeDoor.clone();<br>        door.initializer(r1, r2);<br>        return door;<br>    }<br>}</pre><p>We can use <em>MazePrototypeFactory</em> to create a prototypical or default maze just by initializing it with prototypes of basic maze components.</p><pre>import commoncode.*;<br><br>public class MainPrototypeFactory {<br>    public static void main(String[] args) {<br>        MazeGame_Factory game;<br>    <br>        MazePrototypeFactory simpleMazeFactory = new MazePrototypeFactory(<br>            new Maze(), <br>            new Wall(), <br>            new Room(1), <br>            new Door(1, 2));<br><br>        Maze maze = game.CreateMaze(simpleMazeFactory);<br>      } <br>}</pre><h3>Known Uses</h3><p>The first widely known application of the pattern in an object- oriented language was in ThingLab, where users could form a composite object and then promote it to a prototype by installing it in a library of reusable objects</p><p>The first widely known application of the pattern in an object-oriented language was in ThingLab, where users could form a composite object and then promote it to a prototype by installing it in a library of reusable objects</p><h3>Related Patterns</h3><p>Prototype and Abstract Factory are competing patterns in some ways, as we discuss at the end of this chapter. They can also be used together, however. An Abstract Factory might store a set of prototypes from which to clone and return product objects.</p><p>Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.</p><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/prototype-object-creational/"><em>https://federicobruzzone.github.io</em></a><em> on May 8, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21045dccc0d9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/prototype-class-creational-21045dccc0d9">Prototype — Class Creational</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Vim as your C/C++ IDE]]></title>
            <link>https://blog.devgenius.io/make-vim-as-your-c-c-ide-2be2de70819e?source=rss-6ec37c982cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be2de70819e</guid>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[editor]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Federico Bruzzone]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 00:00:49 GMT</pubDate>
            <atom:updated>2023-05-19T17:42:42.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkGRdf8UM4jxYCrSkhxqkQ.png" /></figure><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/vim/make-vim-as-your-cc++-ide/"><em>https://federicobruzzone.github.io</em></a><em> on April 26, 2023.</em></p><blockquote><em>This procedure can be very similar for </em><em>VSCode and </em><em>Fleet editors. In this case, you should only create the </em><em>compile_commands.json file, and this procedure is illustrated in the subsection, but I suggest you read the whole post.</em></blockquote><p>It happened to me in the past that I had to configure <em>Vim</em> to manage C projects with some external library, and after lots of useless attempts, I gave up setting it up.</p><p>I am currently attending a university course called Advanced in Operating Systems. I am using a STM32 microcontroller and ST provides an “Eclipse 2010 based” IDE with lots of proprietary libraries, but as a <em>Vim</em> programmer writing even 10 lines of code on this IDE made me frustrated. So, I decided to try again, and as you can imagine if you are reading this blog post, I succeeded!</p><h3>Requirements</h3><ol><li>Make sure use Vim &gt;= 8.1.1719 or Neovim &gt;= 0.4.0 and make</li><li>Install nodejs &gt;= 14.14:</li></ol><p>curl -sL install-node.vercel.app/lts | bash</p><h3>Configuration</h3><h3>coc</h3><p><a href="https://github.com/neoclide/coc.nvim">coc GitHub</a></p><p>Firstly, you should have a plug-in installed. I am currently using <strong>vim-plug</strong> as plug-in manager, but you can use any other.</p><p>In my case, I added it to my .vimrc file</p><pre>Plug &#39;https://github.com/neoclide/coc.nvim&#39;</pre><p>and run :PlugInstall</p><p>After that restart <strong>Vim </strong>and make sure you have installed two important extensions, which are coc-json and coc-tsserver using :CocList extensions, if not run :CocInstall coc-json coc-tsserver</p><h3>coc-clangd</h3><p><a href="https://github.com/clangd/coc-clangd">coc-clangd GitHub</a></p><p>As you can imagine, is an extension of coc.nvim like the previous two, and you can install it just by running :CocInstall coc-clangd, after that coc-clangd will try to find clangd from your $PATH, if not found, you can run :CocCommand clangd.install to install the latest release from GitHub.</p><p>At this point, you should be able to create ~/.vim/coc-settings.json file and add the code below to it</p><pre>{<br>  &quot;languageserver&quot;: {<br>    &quot;ccls&quot;: {<br>      &quot;command&quot;: &quot;ccls&quot;,<br>      &quot;args&quot;: [&quot;--log-file=/tmp/ccls.log&quot;, &quot;-v=1&quot;],<br>      &quot;filetypes&quot;: [&quot;c&quot;, &quot;cc&quot;, &quot;cpp&quot;, &quot;c++&quot;, &quot;objc&quot;, &quot;objcpp&quot;],<br>      &quot;rootPatterns&quot;: [&quot;.ccls&quot;, &quot;compile_commands.json&quot;],<br>      &quot;initializationOptions&quot;: { <br>         &quot;cache&quot;: {<br>           &quot;directory&quot;: &quot;/tmp/ccls&quot;<br>         },<br>         &quot;client&quot;: {<br>          &quot;snippetSupport&quot;: true<br>         }<br>       }<br>    }<br>  },<br>  &quot;clangd.path&quot;: &quot;~/.config/coc/extensions/coc-clangd-data/install/15.0.6/clangd_15.0.6/bin/clangd&quot;,<br>}</pre><p>Obviusly, you should change the value of the “clangd.path” field with your version, it may be something like &quot;clangd.path&quot;: &quot;~/.config/coc/extensions/coc-clangd data/install/&lt;version&gt;/clangd_&lt;version&gt;/bin/clangd&quot; (note &lt;version&gt; on the string).</p><p>I do not want to bore you by explaining whole fields of the json file, the only thing I would like to say to you is that this code is used to specify the type of language server ( ccls in this case) and its behavior.</p><h3>ccls</h3><p><a href="https://github.com/MaskRay/ccls">ccls GitHub</a></p><p>Basically, which originates from cquery, is a C/C++/Objective-C language server.</p><p>It provides:</p><ul><li>code completition (with both signature help and snippets)</li><li>definition/reference, and other cross references</li><li>diagnostics and code actions</li><li>semantic highlighting and preprocessor skipped regions</li><li>diagnostics and code actions</li><li>semantic highlighting and preprocessor skipped regions</li></ul><p>and the other many usefull things.</p><p>You must install it because, as you can see in the coc-settings.json, the language server specified is ccls.</p><p>You can do it using your package manager, in my case</p><pre>sudo apt-get install ccls</pre><p><strong>Setup</strong></p><p>Typically, ccls indexes an entire project. In order for this to work properly, ccls needs to be able to obtain the source file list and their compilation command lines.</p><p><strong>How </strong><strong>ccls obtains sources and compilation commands</strong></p><p>There are two main ways this happens:</p><ol><li>Provide compile_commands.json at the project root</li><li>Provide a .ccls file.</li></ol><p>If neither exists, then when ccls starts it will not index anything: instead it will wait for LSP clients to open files and index only those files.</p><p>I prefer use the first one, and to do that if you are using Makefile as build system for your C/C++ project you can generate compile_commands.json automatically with <a href="https://github.com/rizsotto/Bear">bear</a> command, I will explain in detail how in the next paragraph.</p><p>If you are not using Makefile as build system, there are lots of ways to generate this file, for example with CMake, compiledb, scan-build and so on. I suggest you to take a look <a href="https://github.com/MaskRay/ccls/wiki/Project-Setup">here</a>.</p><h3>bear</h3><p><a href="https://github.com/rizsotto/Bear">bear GitHub</a></p><p><a href="https://github.com/rizsotto/Bear">Bear</a> is a tool that generates a compilation database for clang tooling. The compilation database is our compile_commands.json, a simple json file.</p><p>The JSON compilation database is used in the clang project to provide information on how a single compilation unit is processed. With this, it is easy to re-run the compilation with alternate programs.</p><p>Some build system natively supports the generation of JSON compilation database. For projects which does not use such build tool, Bear generates the JSON file during the build process.</p><p>You can install it using your package manager, in my case</p><pre>sudo apt-get install bear</pre><h3>Use case</h3><p>Consider this simple C project, but it can be extended to much larger projects.</p><p>I assure you that it works exactly as in the case I am going to illustrate now, the only important thing is to write your makefile correctly, but this is also obvious because otherwise your project would not compile. :D</p><pre>.<br>├── inc/<br>│   └── main.h<br>├── src/<br>│   └── main.c<br>└── Makefile</pre><pre>// main.h<br><br>#define TEST &quot;test&quot;</pre><pre>// main.c<br><br>#include &quot;main.h&quot;<br>#include &lt;stdio.h&gt;<br><br>int main() {<br>    int *ptrarray[4];<br>    int w = 100, x = 200, y = 300, z = 400;<br><br>    ptrarray[0] = &amp;w;<br>    ptrarray[1] = &amp;x;<br>    ptrarray[2] = &amp;y;<br>    ptrarray[3] = &amp;z;<br><br>    for (int i = 0; i&lt; 4; i++) {<br>         printf(&quot;The value %d has the adddress %d\n&quot;, *ptrarray[i], ptrarray[i]);<br>    }<br><br>    printf(&quot;I am printing a variable of main.h file %d&quot;, &amp;TEST);<br>    <br>    return 0;<br>}</pre><p>It is a silly file that prints the values and memory area of the elements of an array.</p><pre>CC = gcc<br>CFLAGS = -Wall<br><br>INC_DIR = inc<br>SRC_DIR = src<br><br>SRC_FILES = $(wildcard $(SRC_DIR)/*.c)<br>INC_FILES = $(wildcard $(INC_DIR)/*.h)<br><br>main: $(SRC_FILES) $(INC_FILES)<br> $(CC) $(CFLAGS) $(SRC_FILES) -o main -I$(INC_DIR)</pre><p>But, the main problem is that <em>Vim</em>, specially ccls and coc tells me that I have an error in line 1 of the main.c, and as you can imagine, the error is main.h file not found, and this problem is difficult to manage manually, and it becomes even more difficult to manage if the project uses external libraries.</p><p>This problem is also blocking all the LSP features, for example go-to-definition, go-to-implementation etc…</p><p>To solve it, we just have to run the</p><pre>bear -- make</pre><p>command, and it will generate the compile_commands.json and there will be no more errors.</p><pre>.<br>├── inc/<br>│   └── main.h<br>├── src/<br>│   └── main.c<br>├── compile_commands.json<br>├── main*<br>└── Makefile</pre><p>and compile_commands.json will be something like this</p><pre>[<br>  {<br>    &quot;arguments&quot;: [<br>      &quot;/usr/bin/gcc&quot;,<br>      &quot;-c&quot;,<br>      &quot;-Wall&quot;,<br>      &quot;-Iinc&quot;,<br>      &quot;-o&quot;,<br>      &quot;main&quot;,<br>      &quot;src/main.c&quot;<br>    ],<br>    &quot;directory&quot;: &quot;/home/c_project&quot;,<br>    &quot;file&quot;: &quot;/home/c_project/src/main.c&quot;,<br>    &quot;output&quot;: &quot;/home/c_project/main&quot;<br>  }<br>]</pre><p>For bigger projects, so for example the one I am currently working on for the Advanced in OS course that uses a lot of external libraries, this file can reach even 600 lines.</p><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/vim/make-vim-as-your-cc++-ide/"><em>https://federicobruzzone.github.io</em></a><em> on April 26, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be2de70819e" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/make-vim-as-your-c-c-ide-2be2de70819e">Make Vim as your C/C++ IDE</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Method pattern — Class Creational]]></title>
            <link>https://blog.devgenius.io/factory-method-pattern-class-creational-6c29e66b5c3a?source=rss-6ec37c982cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c29e66b5c3a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Federico Bruzzone]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 07:43:15 GMT</pubDate>
            <atom:updated>2023-05-14T09:34:54.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>Factory Method pattern — Class <strong>Creational</strong></h3><h4>A summary of GoF Design Patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*y-Vm5CxhYS9GKZmP_600jQ.png" /><figcaption>By <strong>Dmitry Zhart</strong> (<a href="https://refactoring.guru/">refactoring.guru</a>)</figcaption></figure><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/factory-method-pattern-class-creational/"><em>https://federicobruzzone.github.io</em></a><em> on February 03, 2023.</em></p><h3>Intent</h3><p>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.</p><h3><strong>Also Known As</strong></h3><p>Virtual Constructor</p><h3>Motivation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ax9jVuU4ZgcVh7CIZVPH8A.png" /></figure><p>Framework use abstract classes to define and maintain relationship between objects. A framework is often responsible for creating these objects as well.</p><p>Consider a framework for applications that can present multiple documents to the user. Two key abstractions in this framework are the classes Application and the Document. Both classes are abstract, and clients have to subclass them to realize their application-specific implementations. The Application class is responsible for managing Documents and will create them as required.</p><p>Because the particular Document subclass to instantiate is application-specific, the Application class can’t predict the subclass of Document to instantiate — the Application class only knows <em>when</em> a new document should be created, not <em>what kind </em>of Document to create.</p><p>The Factory Method pattern offers a solution. It encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework.</p><p>Application subclass redefine an abstract CreateDocument operation on Application to return the appropriate Document subclass. Once an Application subclass is instantiated, it can then instantiate application-specific Documents without knowing their class. We call CreateDocument a <strong>factory method<em> </em></strong>because it is responsible for “manufacturing” an object.</p><h3>Applicability</h3><p>Use the Factory Method pattern when</p><ul><li>a class can’t anticipate the class of obejcts it must create.</li><li>a class wants its subclasses to specify the objects it creates.</li><li>classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.</li></ul><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ej1tVZWLb8s8qni8UUzGzg.png" /></figure><h3>Participants</h3><h4>Product</h4><p><em>(Document)</em></p><ul><li>defines the interface of objects the factory method creates.</li></ul><h4>ConcreteProduct</h4><p><em>(MyDocument)</em></p><ul><li>implements the Product interface</li></ul><h4>Creator</h4><p><em>(Application)</em></p><ul><li>declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.</li><li>may call the factory method to create a Product object.</li></ul><h4>ConcreteCreator</h4><p><em>(MyApplication)</em></p><ul><li>overrides the factory method to return an instance of a ConcreteProduct.</li></ul><h3><strong>Collaborations</strong></h3><ul><li>Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.</li></ul><h3>Consequences</h3><p>Factory methods eliminate the need to bind application-specific classes into your code. The code only deals with the Product interface; therefore it can wok with any user-defined ConcreteProduct classes.</p><p>A potential disadvantage of factory methods is that clients might have to subclass a Creator classes just to create a particular ConcreteProduct object.</p><p>Here are two additional consequences of the Factory Method pattern:</p><ol><li><em>Provides hooks for subclasses</em>. Creating objects inside a class with a factory method is always more flexible than crating an object directly. Factory method gives subclasses a hook for providing an extend version of an object.</li><li><em>Connects parallel class hierarchies</em>. Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class. Consider graphical figures that can be manipulated interactively; that is, thay can be stretched, moved, or rotated using the mouse. Implementing suh interactions ins’t always easy. It often requires storing and updating information records the state of the manipulation. This state is needed only during manipulation.</li></ol><p>With this constraints, it’s better to use separate Manipulator object that implements the interaction and keeps track of any manipulation-specific state that’s needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHYXS9pxJHr6elDM0NV6tg.png" /></figure><p>The Figure class provides a CreateManipulator factory method that lets client create a Figure’s corresponding Manipulator. Figure subclasses override this method to return an instance of the Manipulator subclass that’s right for them. Alternatively, the Figure class may implement CreateManipulator to return a default Manipulator instance, and Figure subclasses may simply inherit default.</p><p>Notice how the factory method defines the connection between the two class hierarchies. It localize knowledge of which classes belong together.</p><h3>Implementation</h3><p>Consider the following issue when applying the Factory Method pattern:</p><ol><li><em>The two varieties. </em>The two main variations of the Factory Method pattern are (1) the case when the Creator class is an abstract class and does not provide an implementation for the factory method it declares, and (2) the case when the Creator is a concrete class and provide a default implementation for the factory method. The first case <em>requires</em> subclasses to define an implementation, because there is no reasonable default. In the second case, the concrete Creator uses the factory method primarily for flexibility.</li><li><em>Parameterized factory methods. </em>Another variation on the pattern lets the factory method create <em>multiple</em> kinds of products. The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates will share the Product interface.</li><li><em>Language-specific variants and issues.</em> Different languages lend themselves to other interesting variations and caveats. Smalltalk programs often use a method that returns the class of the object to be instantiated. A Creator factory method can use this value to create a product, and a ConcreteCreator may store or even compute this value. The result is an even later binding for the type of ConcreteProduct to be instantiated.</li><li><em>Using templates to avoid subclassing. </em>Another potential problem with factory methods is that they might force you to subclass just to create the appropriate Product objects. Another way to get around this in C++ is to provide a template subclass of Creator that’s parameterized by the Product class.</li><li><em>Naming conventions</em>. It’s good practice to use naming conventions that make it clear you’re using factory methods.</li></ol><h3>Sample Code</h3><p>To better understand the following code and the classes used look</p><p><a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode"><strong>here🔗!</strong></a></p><p>The function <a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode">CreateMaze</a> builds and returns a maze. One problem with this function is that it hard-codes the classes of maze, rooms, doors, and walls.We’ll introduce factory methods to let subclasses choose these components.</p><p>First we’ll define factory methods in <em>MazeGame</em> for creating the maze,room,wall, and door objects:</p><pre>import commoncode.*;<br><br>public class MazeGame_Factory {<br>  <br>  public MazeGame_Factory() {}<br>  <br>  public Maze MakeMaze() <br>    { return new Maze(); }<br>  <br>  public Wall MakeWall() <br>    { return new Wall(); }<br>  <br>  public Room MakeRoom(int n) <br>    { return new Room(n); }<br>  <br>  public Door MakeDoor(Room r1, Room r2)<br>    { return new Door(r1, r2); }<br>  <br>  public Maze CreateMaze() {<br>    Maze aMaze   = this.MakeMaze();<br>    Room r1      = this.MakeRoom(1);<br>    Room r2      = this.MakeRoom(2);<br>    Door theDoor = this.MakeDoor(r1, r2);<br><br>    r1.SetSide(Direction.North, this.MakeWall());<br>    r1.SetSide(Direction.East,  theDoor);<br>    r1.SetSide(Direction.South, this.MakeWall());<br>    r1.SetSide(Direction.West,  this.MakeWall());<br><br>    r2.SetSide(Direction.North, this.MakeWall());<br>    r2.SetSide(Direction.East,  this.MakeWall());<br>    r2.SetSide(Direction.South, this.MakeWall());<br>    r2.SetSide(Direction.West,  theDoor);<br><br>    aMaze.AddRoom(r1);<br>    aMaze.AddRoom(r2);<br><br>    return aMaze;<br>  }<br><br>}</pre><p>Each factory method returns a maze component of a given type. <em>MazeGame</em> provides default implementations that return the simplest kinds of maze, rooms, walls, and doors.</p><p>Now we have to rewrite <em>CreateMaze</em> to use these factory methods.</p><h3>Known Uses</h3><p>Factory methods pervade toolkits and frameworks.The preceding document example is a typical use in MacApp and ET++ [WGM88]. The manipulator example is from Unidraw.</p><p>Class View in the Smalltalk-80 Model/View/Controller framework has a method defaultController that creates a controller, and this might appear to be a factory method [Par90]. But subclasses of Viewspecify the class of their default controller by defining defaultControllerClass, which returns the class from which defaultController creates instances. So defaultControllerClass is the real factory method, tKat is, the method that subclasses should override.</p><h3>Related Patterns</h3><p>Abstract Factory is often implemented with factory methods.</p><p>Factory methods are usually called within Template Methods.</p><p>Prototypes don’t require subclassing Creator. However, they often require an Initialize operation on the Product class. Creator uses Initialize to initialize the object. Factory Method doesn’t require such an operation.</p><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/factory-method-pattern-class-creational/"><em>https://federicobruzzone.github.io</em></a><em> on February 03, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c29e66b5c3a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/factory-method-pattern-class-creational-6c29e66b5c3a">Factory Method pattern — Class Creational</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder pattern — Object Creational]]></title>
            <link>https://blog.devgenius.io/builder-object-creational-df35c97ba875?source=rss-6ec37c982cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/df35c97ba875</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Federico Bruzzone]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 07:59:26 GMT</pubDate>
            <atom:updated>2023-05-14T09:33:09.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Builder pattern — Object Creational</h3><h4>A summary of GoF Design Patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vP4cz-Ns2C-JASqjeycOdw.png" /><figcaption>By <strong>Dmitry Zhart</strong> (<a href="https://refactoring.guru/">refactoring.guru</a>)</figcaption></figure><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/builder-pattern-object-creational/"><em>https://federicobruzzone.github.io</em></a><em> on January 13, 2023.</em></p><h3>Intent</h3><p>Separate the construction of a complex object from its representation so that the same construction process can create different representations.</p><h3>Also Known As</h3><p>…</p><h3>Motivation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwgCLbk3FG727ppcUb8fSQ.png" /></figure><p>A reader for the RTF (Rich Text Format) document exchange format should be able to convert RTF to many text formats. The problem is the number of possible conversions is open-ended.</p><p>A solution is to configure the RTFReader class with TextConverter object that converts RTF to another textual representation. As the RTFReader perses the RTF document, it uses the TextConverter to perform the conversion. Whenever the RTFReader recognizes an RTF token, it issues a request to the TextConverter to convert the token.</p><p>Subclasses of TextConverter specialize in different conversions and formats. For example, ASCIIConverter ignores requests to convert anything except plain text.</p><p>Each kind of converter class takes the mechanism for creating and assembling a complex object and puts it behind an abstract interface. The converter is separate from the reader.</p><p>The Builder pattern captures all these relationships. Each converter is called a <strong>builder </strong>in the pattern, and the reader is called the <strong>director</strong>. The Builder pattern separates the algorithm for interpreting a textual format from how a converted format gets created and represented.</p><h3>Applicability</h3><p>Use the Builder pattern when</p><ul><li>the algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled.</li><li>the construction process must allow different representations for the object that is constructed.</li></ul><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3m1IiNlOY0kGfQ4Cebpbg.png" /></figure><h3>Participants</h3><h4><strong>Builder</strong></h4><p><em>(TextConverter)</em></p><ul><li>specifies an abstract interface for creating parts of a Product object.</li></ul><h4>ConcreteBuilder</h4><p><em>(ASCIIConverter, TeXConverter, TextWidgetConverter)</em></p><ul><li>constructs and assembles parts of the product by implementing the Builder interface.</li><li>defines and keeps track of the representation it creates.</li><li>provides an interface for retrieving the product.</li></ul><h4>Director</h4><p><em>(RTFReader)</em></p><ul><li>constructs an object using the Builder interface.</li></ul><h4>Product</h4><p><em>(ASCIIText, TeXText, TextWidget)</em></p><ul><li>represents the complex object under construction. ConcreteBuilder builds the product’s internal representation and defines the process by which it is assembled.</li><li>includes classes that define the constituent parts, including interface for assembling the parts into the final result.</li></ul><h3>Collaborations</h3><ul><li>The client creates the Director object and configures it with the desired Builder object.</li><li>Director norifies the builder whenever a part of the product should be built.</li><li>Builder handles requests from the director and adds parts to the product.</li><li>The client retrieves the product from the builder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*MR-qXjtmGPpLoOevRXVX_Q.png" /></figure><h3>Consequences</h3><p>Here are key consequences of the Builder pattern:</p><ol><li><em>It lets you vary a product’s internal representation. </em>The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product.</li><li><em>It isolates code for construction and representation. </em>The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented. Clients needn’t know anything about the classes that define the product’s internal structure.</li><li><em>It gives you finer control over the construction process. </em>Unlike creational patterns that constructed products in one shot, the Builder pattern constructs the product step by step under the director’s control.</li></ol><h3>Implementation</h3><p>Typically there is an abstract Builder class that defines an operation for each component that a directory may ask it to create.</p><p>Here are other implementation issues to consider:</p><ol><li><em>Assemply and construction interface. </em>Builders construct their products in step-by-step fashion. A key design issue concerns the model for the construction and assembly process. A model where the results of construction requests are simply appended to the product is usually sufficient. But sometimes you might need access to part of the product constructed earlier.</li><li><em>Why no abstract class for products? </em>In common case, the product produced by the concrete builders differ so greatly in their representation that there is little to gain form giving different products a common parent class.</li><li><em>Empty methods as default in Builder. </em>They are defined as empty methods instead, letting clients override only the operation they are interested in.</li></ol><h3>Sample Code</h3><p>To better understand the following code and the classes used look</p><p><a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode"><strong>here🔗!</strong></a></p><p>We will define a variant of the <a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode"><em>CreateMaze</em> </a>member function that takes a builder of class <em>MazeBuilder</em> as an argument.</p><p>The <em>MazeBuilder </em>class defines the following interface for building mazes:</p><pre>import commoncode.*;<br><br>public class MazeBuilder {<br>    <br>  protected MazeBuilder() {}<br>    <br>  public void BuildMaze() {}<br><br>  public void BuildRoom(int room) {}<br><br>  public void BuildDoor(int roomFrom, int roomTo) {}<br> <br>  public Maze GetMaze() { return null; }<br><br>}</pre><p>This interface can create three thing: (1) the maze, (2) rooms with a particular room number and (3) doors between numbered rooms. The <em>GetMaze </em>operation returns the maze to the client.</p><p>All the maze-building operations of <em>MazeBuilder </em>do nothing by default.</p><p>Given the <em>MazeBuilder </em>interface, we can change the <em>CreateMaze</em> member function to take this builder as a parameter.</p><pre>import commoncode.*;<br><br>public class MazeGame_Builder {<br>    <br>  public Maze CreateMaze(MazeBuilder builder) {<br>    builder.BuildMaze();<br>    <br>    builder.BuildRoom(1);<br>    builder.BuildRoom(2);<br>    builder.BuildDoor(1, 2);<br>    <br>    return builder.GetMaze();<br>  }<br><br>}</pre><p>Compare this version of <em>CreateMaze </em>with the <a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/blob/main/static/design-pattern/commoncode/MazeGame_First.java">original</a>. Notice how the builder hides the internal representation of the Maze. This make it easier to change the way a maze is represented, since none of the clients of <em>MazeBuilder </em>has to be changed.</p><p>Like the other creational patterns, the Builder pattern encapsulates how objects get created. That means we can reuse <em>MazeBuilder </em>to build different kind of mazes.</p><p>Note that <em>MazeBuilder</em> does not create mazes itself; it main purpose is just to define an interface for creating mazes. It defines empty implementations primarily for convenience. Subclasses of <em>MazeBuilder</em> so the actual work.</p><p>The subclass <em>StandardMazeBuilder</em> is an implementation that builds simple mazes.</p><pre>import commoncode.*;<br><br>public class StandardMazeBuilder extends MazeBuilder {<br>    <br>  private Maze _currentMaze;<br><br>  public StandardMazeBuilder() {<br>    this._currentMaze = null;<br>  }<br><br>  @Override public void BuildMaze() {<br>    this._currentMaze = new Maze();<br>  }<br><br>  @Override public void BuildRoom(int n) {<br>    if (_currentMaze.RoomNo(n) != null) {<br>      Room room = new Room(n);<br>      this._currentMaze.AddRoom(room);<br><br>      room.SetSide(Direction.North, new Wall());<br>      room.SetSide(Direction.South, new Wall());<br>      room.SetSide(Direction.East,  new Wall());<br>      room.SetSide(Direction.West,  new Wall());<br>    }<br>  }<br><br>  @Override public void BuildDoor(int n1, int n2) {<br>    Room r1 = this._currentMaze.RoomNo(n1);<br>    Room r2 = this._currentMaze.RoomNo(n2);<br>    Door d = new Door(r1, r2);<br><br>    r1.SetSide(this.CommonWall(r1, r2), d);<br>    r2.SetSide(this.CommonWall(r2, r1), d);<br>  }<br><br>  private Direction CommonWall(Room r1, Room r2) { <br>    return null;<br>  }<br><br>  @Override public Maze GetMaze() {<br>    return this._currentMaze;<br>  }<br><br>}</pre><p><em>CommonWall</em> is a utility operation that determines the direction of the common wall between two rooms.</p><p>Clients can now use <em>CreateMaze</em> in conjunction with <em>StandardMazeBuilder </em>to create a maze:</p><pre>import commoncode.*;<br><br>public class ClientBuilder {<br>  <br>  public static void main(String[] args) {<br>    Maze maze;<br>    MazeGame_Builder game = new MazeGame_Builder();<br>    StandardMazeBuilder builder = new StandardMazeBuilder();<br><br>    game.CreateMaze(builder);<br>    maze = builder.GetMaze();<br>  }<br><br>}</pre><p>We could have put all the <em>StandardMazeBuilder</em> operations in <em>Maze</em> and let each <em>Maze</em> build itself. But making <em>Maze</em> smaller makes it easier to understand and modify, and <em>StandardMazeBuilder</em> is easy to separate from <em>Maze</em>.</p><h3><strong>Known Uses</strong></h3><p>The RTF converter application is from ET++ [WGM88]. Its text building block uses a builder to process text sorted in the RTF format.</p><p>Builder is a common pattern in Smalltalk-80 [Par90]:</p><ul><li>The Parser class in the compiler subsystem is a Director that takes a ProgramNodeBuilder object as an argument.</li><li>ClassBuilder is a builder that Classes use to create subclasses for themselves.</li><li>ByteCodeStream is a builder that creates a compiled method as a byte array.</li></ul><p>The Service Configurator framework from the Adaptive Communications Environment uses a builder to construct network service components that are linked into a server at run-time [SS94].</p><h3>Related Patterns</h3><p>Abstract Factory is similar to Builder in that it too may construct complex object. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract Factory’s emphasis is on families of product objects. Builder returns the product as a final step, but as far as Abstract Factory pattern is concerned, the product gets returned immediately.</p><p>A Composite is what the builder often builds.</p><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/builder-pattern-object-creational/"><em>https://federicobruzzone.github.io</em></a><em> on January 13, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df35c97ba875" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/builder-object-creational-df35c97ba875">Builder pattern — Object Creational</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Factory pattern — Object Creational]]></title>
            <link>https://blog.devgenius.io/abstract-factory-object-creational-7c25302d3913?source=rss-6ec37c982cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c25302d3913</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Federico Bruzzone]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 13:36:15 GMT</pubDate>
            <atom:updated>2023-05-14T09:33:38.179Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Abstract Factory pattern — Object Creational</strong></h3><h4>A summary of GoF Design Patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*cbPN1zLXmnJOJuvS.png" /><figcaption>By <strong>Dmitry Zhart </strong>(<a href="https://refactoring.guru/">refactoring.guru</a>)</figcaption></figure><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/abstract-factory-pattern-object-creational/"><em>https://federicobruzzone.github.io</em></a><em> on January 02, 2023.</em></p><h4>Intent</h4><p>Provide an interface for creating families of related or dependent objects without specifying their concrete class.</p><h3>Also Known As</h3><p>Kit</p><h3>Motivation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCjuNN2j5rC8EPcKJIkjmA.png" /></figure><p>Consider a user interface toolkit that supports multiple look-and-feel standards. Different look-and-feel define different appearances and behaviors for user interface “widgets” like scroll bars, windows, and buttons. Instantiating look-and-feel-specific classes of widgets throughout the application makes it hard to change the look and feel later.</p><p>We can solve this problem by defining an abstract WidgetFactory class that declares an interface for creating each basic kind of widget. There is also an abstract class for each kind of widget, and concrete subclasses implement widgets for specific look-and-feel standards. WidgetFactory’s interface has an operation that returns a new widget object for each abstract widget class. Clients call these operations to obtain widget instances.</p><p>There is a concrete subclass of WidgetFactory for each look-and-feel standard. Client create widgets solely through the WidgetFactory interface and have no knowledge of the classes that implement widget for a particular look and feel.</p><p>A WidgetFactory also enforces dependencies between the concrete widget classes. A <strong>Dummy </strong>scroll bar should be used with a <strong>Dummy </strong>button and a <strong>Dummy </strong>text editor, and that constraint is enforced automatically as a consequence of using a <strong>DummyWidgetFactory</strong>.</p><h3>Applicability</h3><p>Use the Abstract Factory pattern when</p><ul><li>a system should be independent of how its product are created, composed, and represented.</li><li>a system should be configured with one of multiple families of products.</li><li>a family of related product objects is designed to be used together, and you need to enforce this constraint.</li><li>you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.</li></ul><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hE9xQlWjqVsciB_pALkqRw.png" /></figure><h3>Participants</h3><h4><strong>AbstractFactory</strong></h4><p><em>(WidgetFactory)</em></p><ul><li>declares an interface for operations that create abstract product objects.</li></ul><h4><strong>ConcreteFactory</strong></h4><p><em>(DummyWidgetFactory, TWidgetFactory)</em></p><ul><li>implements the operations to create concrete product objects.</li></ul><h4><strong>AbstractProduct</strong></h4><p><em>(Window, ScrollBar)</em></p><ul><li>declares an interface for a type of product object.</li></ul><h4><strong>ConcreteProduct</strong></h4><p><em>(DummyWindow, DummyScrollBar)</em></p><ul><li>defines a product object to be created by the corresponding concrete factory.</li><li>implements the AbstractProduct interface.</li></ul><h4><strong>Client</strong></h4><ul><li>uses only interfaces declared by AbstractFactory and AbstractProduct classes.</li></ul><h3>Collaborations</h3><ul><li>Normally a single instance of a ConcreteFactory class is created at run-time. This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory.</li><li>AbstractFactory defers creation of product objects to its ConcreteFactory subclass.</li></ul><h3>Consequences</h3><p>The Abstract Factory pattern has the following benefits and liabilities:</p><ol><li><em>It isolates concrete classes. </em>The abstract Factory pattern help you control the classes of object than an application creates. Clients manipulate instances through their abstract interfaces.</li><li><em>It makes exchanging product families easy. </em>The class of concrete factory appears only once in an application — that is, where it’s instantiated. This makes it easy to change the concrete factory an application uses.</li><li><em>It promotes consistency among products. </em>When product objects in a family are designed to work together, it is important that an application use objects from only one family at a time. AbstractFactory makes this easy to enforce.</li><li><em>Supporting new kind of products is difficult. </em>Extending abstract factories to produce new kinds of Products is not easy. Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses. (Solution in the next section)</li></ol><h3>Implementation</h3><p>Here are some useful techniques for implementing the Abstract Factory pattern.</p><ol><li><em>Factories as singletons.</em> An application typically needs only one instance of a ConcreteFactory per product family.</li><li><em>Creating the products. </em>AbstractFactory only declares an <em>interface </em>for creating products. It’s up to ConcreteProduct subclasses to actually create them. The most common way to do this is to define a factory method for each product. A concrete factory will specify its products by overriding the factory method for each. While this implementation is simple, it requires a new concrete factory subclass for each product even if the product families differ only slightly. In many product families are possible, the concrete factory can be implemented using Prototype pattern.</li><li><em>Defining extensible factories. </em>AbstractFactory usually defines a different operation for each kind of product it can produce. Adding a new kind of product requires changing the AbstractFactory interface and all the classes that depends on it. A more flexible but less safe design is to add a parameter to operations that create objects. This parameter specifies the kind of object to be created.</li></ol><p>An inherent problem remains: All products are returned to the client with the <em>same </em>abstract interface as given by the return type. The client will not be able to differentiate of make safe assumption about the class of a product. The client could perform a downcast, that is not always feasible of safe, because the downcasting can fail.</p><h3>Sample Code</h3><p>We will apply the Abstract Factory pattern to creating the mazes.</p><p>To better understand the following code and the classes used look</p><p><a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode"><strong>here🔗!</strong></a></p><p>Class <em>MazeFactory </em>can create components of mazes. It build rooms, walls, and doors between rooms. For instance, it might be used by a program that builds mazes randomly. Programs that build mazes take a <em>MazeFactory</em> as an argument so that the programmer can specify the classes of rooms, walls, and doors to construct.</p><pre>import commoncode.*;<br><br>public class MazeFactory {<br><br>  public MazeFactory() {}<br><br>  public Maze MakeMaze() <br>    { return new Maze(); }<br><br>  public Wall MakeWall() <br>    { return new Wall(); }<br><br>  public Room MakeRoom(int n) <br>    { return new Room(n); }<br><br>  public Door MakeDoor(Room r1, Room r2)<br>    { return new Door(r1, r2); }<br><br>}</pre><p>Here is a version of <em>CreateMaze </em>that take <em>MazeFactory</em> as a parameter. <em>CreateMaze </em>builds a small maze consisting of two rooms with a door between them.</p><pre>import commoncode.*;<br><br>public class MazeGame_Factory {<br><br>  public Maze CreateMaze(MazeFactory factory) {<br>    Maze aMaze   = factory.MakeMaze();<br>    Room r1      = factory.MakeRoom(1);<br>    Room r2      = factory.MakeRoom(2);<br>    Door theDoor = factory.MakeDoor(r1, r2);<br><br>    r1.SetSide(Direction.North, factory.MakeWall());<br>    r1.SetSide(Direction.East,  theDoor);<br>    r1.SetSide(Direction.South, factory.MakeWall());<br>    r1.SetSide(Direction.West,  factory.MakeWall());<br><br>    r2.SetSide(Direction.North, factory.MakeWall());<br>    r2.SetSide(Direction.East,  factory.MakeWall());<br>    r2.SetSide(Direction.South, factory.MakeWall());<br>    r2.SetSide(Direction.West,  theDoor);<br><br>    aMaze.AddRoom(r1);<br>    aMaze.AddRoom(r2);<br><br>    return aMaze;<br>  }     <br>  <br>}</pre><p>Now suppose we want to make a maze game in which a room can have a bomb set in it, and if the bomb goes off, it will damage the walls.</p><p>We can make a subclass of <em>Room </em>(<a href="https://github.com/FedericoBruzzone/federicobruzzone.github.io/tree/main/static/design-pattern/commoncode">here 🔗</a>) keep track if a room has a bomb in it.</p><pre>import commoncode.*;<br><br>public class RoomWithABomb extends Room {<br>  <br>  int bombDamage;<br><br>  public RoomWithABomb(int roomNo) {<br>    super(roomNo);<br>  }  <br><br>  public void setBombDamage(int bombDamage) {<br>    this.bombDamage = bombDamage;<br>  } <br><br>}</pre><p>We also need a subclass of <em>Wall </em>to keep track of the damage.</p><pre>import commoncode.*;<br><br>public class BombedWall extends Wall {<br>  <br>  int wallDamage = 0;<br>  <br>  public BombedWall() {<br>    super();<br>  }  <br><br>  public void hitWall(int bombDamage) {<br>    this.wallDamage = bombDamage;<br>  }<br><br>}</pre><p>The last class we defined is <em>BombedMazefactory</em>, a subclass of <em>MazeFactory </em>(defined above). This class only need to override two functions:</p><pre>import commoncode.*;<br><br>public class BombedMazeFactory extends MazeFactory {<br>     <br>  public Wall MakeWall() <br>    { return new BombedWall(); }<br><br>  public Room MakeRoom(int n) <br>    { return new RoomWithABomb(n); }<br><br>}</pre><p>To build a simple maze that can contains bomb or not, we simply call <em>CreateMaze</em> with a <em>BombedMazeFactory </em>or <em>MazeFactory</em>.</p><pre>public class MainAbstractFactory {<br><br>  public static void main(String[] args) {<br>    MazeGame_Factory game = new MazeGame_Factory();<br><br>    MazeFactory factory = new MazeFactory();<br>    BombedMazeFactory bombedFactory = new BombedMazeFactory();<br><br>    game.CreateMaze(bombedFactory /* factory */);<br>  }  <br>  <br>}</pre><p>Notice that the <em>MazeFactory </em>is just a collection of factory methods. This is the most common way to implement the Abstract Factory pattern. Also note that <em>MazeFactory </em>is not an abstract class; it acts as both AbstractFactory <em>and</em> ConcreteFactory.</p><h3>Known Uses</h3><p>InterViews uses the “Kit” suffix [Lin92] to denote AbstractFactory classes. It defines WidgetKit and DialogKit abstract factories for generating look-and-feel-specific user interface objects. InterViews also includes a LayoutKit that generates different composition objects depending on the layout desired.</p><h3>Related Patterns</h3><p>AbstractFactory classes are often implemented with factory methods, but they can also implemented using Prototype.</p><p>A concrete factory is often a singleton.</p><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/abstract-factory-pattern-object-creational/"><em>https://federicobruzzone.github.io</em></a><em> on January 02, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c25302d3913" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/abstract-factory-object-creational-7c25302d3913">Abstract Factory pattern — Object Creational</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns  —  Introduction]]></title>
            <link>https://blog.devgenius.io/design-patterns-introduction-6f12fd2c7c92?source=rss-6ec37c982cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f12fd2c7c92</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Federico Bruzzone]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 22:59:10 GMT</pubDate>
            <atom:updated>2023-05-14T09:29:57.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — Introduction</h3><h4>A summary of GoF Design Patterns</h4><figure><img alt="Cover art © 1994 M.C. Escher / Cordon Art — Baarn — Holland. All right reserved." src="https://cdn-images-1.medium.com/max/609/1*q1obEB_v7167I10GVkBy-g.jpeg" /><figcaption>Cover art © 1994 M.C. Escher / Cordon Art — Baarn — Holland. All right reserved.</figcaption></figure><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/design-patterns-introduction/"><em>https://federicobruzzone.github.io</em></a><em> on December 19, 2022.</em></p><p>Before I start talking about what are the design patterns I would like to dedicate a few words to this picture that you can see in the official cover of <strong>Design Pattern — Elements of Reusable Object-Oriented Software.</strong></p><p>If you did not know who <strong>Maurits Cornelis Escher</strong> was, he was an one of the greatest artist of the twentieth century who made mathematically inspired woodcuts, lithographs, and mezzotints.</p><blockquote>His work features mathematical objects and operations including impossible objects, explorations of infinity, reflection, symmetry, perspective, truncated and stellated polyhedra, hyperbolic geometry, and tessellations.</blockquote><p>Joking, the description above is extremely consistent with the thought you have when you are a beginner to design patterns. I could talk for hours about what I think about this masterpiece but it is better to move on to the concrete, or rather to the abstract …</p><h3>Contents</h3><ul><li><strong>What Is a Design Pattern?</strong></li><li><strong>Describing Design Patterns</strong></li><li><strong>The Catalog of Design Patterns</strong></li><li><strong>Organizing the Catalog</strong></li><li><strong>How Design Patterns Solve Design Problems</strong></li></ul><h3>What is a Design Pattern?</h3><p>Christofer Alexander says,</p><blockquote>“Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such way that you can use this solution a million times over, without ever doing it the same way twice” [AIS+77, page x]</blockquote><p>Probably the best way to classify design patterns is to talk about their four main elements:</p><ol><li>The <strong>Pattern name </strong>is simply the name that describe the pattern. Usually it is one or two word in relationship with their <strong>Solution</strong> and <strong>Consequences. </strong>Attributing a <strong>Pattern name</strong> we can use this to talk with our colleagues, write a documentation and many other thing without ambiguity.</li><li>The <strong>Problem </strong>describes when we apply the pattern. It might be a representation such as how to implements an algorithm or data structure as an Object.</li><li>The <strong>Solution </strong>describes the elements that we should use to implements the design pattern. These elements could be related to themselves and the collaboration and responsibilities are more important.</li><li>The <strong>Consequences </strong>are the result and trade-off that the design patter should returns.</li></ol><h3>Describing Design Pattern</h3><p><strong>Design Pattern — Elements of Reusable Object-Oriented Software </strong>book describe design patterns using a consistent format. Each pattern is divided into section according to the following template.</p><h4>Pattern Name and Classification</h4><p>A good name is vital, because it will become part of your design vocabulary. The pattern’s classification reflects the scheme I introduce in section <strong>Organizing the Catalog</strong>.</p><h4>Intent</h4><p>Following question: What does the design pattern do? What is its rationale and intent? What particular design issue or problem does is address?</p><h4>Also Known As</h4><p>Other well-known names for the pattern, if any.</p><h4>Motivation</h4><p>A scenario that illustrate a design problem and how the class and object structures in the pattern solve the problem.</p><h4>Applicability</h4><p>What are the situations in which the design pattern can be applied? What are example of poor designs that the pattern can address? How can you recognize these situations?</p><h4>Structure</h4><p>A graphical representation of the classes in the pattern using a notation based on the Object Modeling Technique (OMT) [RBP+91]. I also use interaction diagrams [JCJO92, Boo94] to illustrate sequences of request and collaborations between object.</p><h4>Participants</h4><p>The classes and / or objects participating in the design pattern and their responsibilities.</p><h4>Collaborations</h4><p>How the participants collaborate to carry out their responsibilities.</p><h4>Consequences</h4><p>How does the pattern support its objectives? What are trade-offs and results of using pattern?</p><h4>Implementation</h4><p>What pitfalls, hints, or techniques should you be aware of when implementing the pattern?</p><h4>Sample Code</h4><p>Code fragments that illustrate how you might implement the pattern in C++ or Smalltalk.</p><h4>Known Uses</h4><p>Example of the pattern found in real system.</p><h4>Related Patterns</h4><p>When design pattern are closely related to this one?</p><h3>The Catalog of Design Patterns</h3><ul><li><strong>Abstract Factory </strong>—<strong> </strong>Provide an interface for creating families of related or dependent objects without specifying their concrete classes.</li><li><strong>Adapter </strong>— Convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.</li><li><strong>Bridge </strong>— Decouple an abstraction from its implementation so that the two can very independently.</li><li><strong>Builder </strong>—Separate the construction of a complex object from its representation so that the same construction process can create different representations.</li><li><strong>Chain of Responsibility </strong>— Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving object and pass the request along the chain until an object handles it.</li><li><strong>Command </strong>—<strong> </strong>Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo able operations.</li><li><strong>Composite</strong> — Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly</li><li><strong>Decorator</strong> — Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.</li><li><strong>Facade</strong> — Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.</li><li><strong>Factory Method</strong> — Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.</li><li><strong>Flyweight </strong>—<strong> </strong>Use sharing to support large numbers of fine-grained objects efficiently.</li><li><strong>Interpreter </strong>— Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.</li><li><strong>Iterator</strong> — Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.</li><li><strong>Mediator </strong>—<strong> </strong>Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.</li><li><strong>Memento</strong> — Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.</li><li><strong>Observer</strong> — Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</li><li><strong>Prototype</strong> — Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.</li><li><strong>Proxy </strong>— Provide a surrogate or placeholder for another object to control access to it.</li><li><strong>Singleton</strong> — Ensure a class only has one instance, and provide a global point of access to it.</li><li><strong>State</strong> — Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.</li><li><strong>Strategy </strong>— Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</li><li><strong>Template Method </strong>— Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.</li><li><strong>Visitor </strong>— Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.</li></ul><h3>Organizing the Catalog</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*IS9FVJIi53uJxPb8e3lGGQ.png" /><figcaption>Table 1.1: Design pattern space</figcaption></figure><p>Design pattern vary in their granularity and level of abstraction. The classification helps you to learn the patterns in the catalog faster.</p><p>The book classify design pattern by two criteria (Table 1.1). The first criterion, called <strong>purpose</strong> reflects what a pattern does. Patterns can have either <strong>creational</strong>, <strong>structural</strong>, or <strong>behavioral </strong>purpose. Creational patterns concern the process of object creation. Structural patterns deal with the composition of classes or object. Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility.</p><p>The second criterion, called <strong>scope, </strong>specifies whether the pattern applies primarily to classes or to objects. Class patterns deal with relationship between classes and their subclasses. Object patterns deal with object relationship, which can be changed at run-time and are more dynamic.</p><h3><strong>How Design Patterns Solve Design Problems</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*H_wKtQJifuPNm9WLUK_jhQ.png" /><figcaption>Figure 1.1: Design pattern relationship</figcaption></figure><h4>Finding Appropriate Objects</h4><p>Object-oriented programming are made up of objects. An <strong>object </strong>packages both data and the procedures that operate on that data. The procedures are typically called <strong>methods</strong> or <strong>operations. </strong>An object performs an operation when it receives a <strong>request</strong> from a <strong>client</strong>.</p><p>The hard part of object-oriented design is decomposing a system into objects because there are many factor come into play: encapsulation, granularity, dependency, flexibility, performance, evolution, reusability, and on and on.</p><p>Object oriented design methodologies favor many different approaches. You can write a problem statement and create classes and operations. Or you can focus on the collaboration in your system. Or you can model the real world and translate objects found during analysis into design.</p><p>Design patters help you identify less-obvious abstractions and the objects that can capture them. For example, objects that represent a process or algorithm don’t occur in nature. The <strong>strategy </strong>pattern describes how to implement interchangeable families of algorithms. The <strong>state</strong> pattern represent each state of an entity as an object.</p><h4>Determining Object Granularity</h4><p>Object can vary in size and number. They can represent everything down to the hardware or all the way up to entire software.</p><p>Design patterns address this issue as well. The <strong>facade </strong>pattern describes how to represent complete subsystem as object and the <strong>flyweight </strong>pattern describe how to support huge numbers of object at the finest granularity</p><h4>Specifying Object Interfaces</h4><p>Every operation declared by an object specifies the operation’s name, the objects it takes as parameters, and the operation’s return value. This is known as the operation’s <strong>signature</strong>. The set of all signatures defined by an object’s operations is called the <strong>interface</strong> to the object.</p><p>A <strong>type</strong> is a name used to denote a particular interface. We speak of an object as having the type “Window” if it accepts all requests for the operations defined in the interface named “Window.” Two objects of the same type need only share parts of their interfaces. Interfaces can contain other interfaces as subsets. We say that a type is a <strong>subtype</strong> of another if its interface contains the interface of its <strong>supertype</strong>.</p><p>When a request is sent to an object, the particular operation that’s performed depends on <em>both</em> the request <em>and</em> the receiving object. The run-time association of a request to an object and one of its operations is known as <strong>dynamic binding</strong>.</p><p>Moreover, dynamic binding lets you substitute objects that have identical interfaces for each other at run-time. This substitutability is known as <strong>polymorphism</strong>, and it’s a key concept in object-oriented systems.</p><p>Design patterns help you define interfaces by identifying their key elements and the kinds of data that get sent across an interface.</p><p>For example, the Memento pattern it describes how to encapsulate and save the internal state of an object so that the object can be restored to that state later.</p><h4>Specifying Object Implementations</h4><p>An object’s implementation is defined by its <strong>class.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*io7nj51Rrr-DmhRX6BshMw.png" /></figure><p>Objects are created by <strong>instantiating</strong> a class. The object is said to be an <strong>instance</strong> of the class. The process of instantiating a class allocates storage for the object’s internal data (made up of <strong>instance variables</strong>) and associates the operations with these data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*58SyWmeruAmdw1V3w02k5Q.png" /></figure><p>New classes can be defined in terms of existing classes using <strong>class inheritance</strong>. When a <strong>subclass</strong> inherits from a <strong>parent class</strong>, it includes the definitions of all the data and operations that the parent class defines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*TcK6DIH376iHIMffM1WLnQ.png" /></figure><p>An<strong> abstract class</strong> is one whose main purpose is to define a common interface for its subclasses. An abstract class will defer some or all of its implementation to operations defined in subclasses; hence an abstract class cannot be instantiated. A <strong>concrete class</strong> may <strong>override</strong> an operation defined by its parent class. Overriding gives subclasses a chance to handle requests instead of their parent classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*TzjsymXc1wy1cFmtjx4oiw.png" /></figure><p>A <strong>mixin class</strong> is a class that’s intended to provide an optional interface or functionality to other classes. It’s similar to an abstract class in that it’s not intended to be instantiated. Mixin classes require multiple inheritance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*0oSnhlzbFGqZ_4O0D-VC5w.png" /></figure><h4>Class versus Interface Inheritance</h4><p>It’s important to understand the difference between an object’s <em>class</em> and its <em>type</em>.</p><p>An object’s class defines how the object is implemented. The class defines the object’s internal state and the implementation of its operations. In contrast, an object’s type only refers to its interface – the set of requests to which it can respond. An object can have many types, and objects of different classes can have the same type.</p><p>It’s also important to understand the difference between class inheritance and interface inheritance (or subtyping). Class inheritance defines an object’s implementation in terms of another object’s implementation. In short, it’s a mechanism for code and representation sharing. In contrast, interface inheritance (or subtyping) describes when an object can be used in place of another.</p><p>Many of the design patterns depend on this distinction. For example, in the Composite pattern, Component defines a common interface, but Composite often defines a common implementation. Observer, State, and Strategy are often implemented with abstract classes.</p><h4>Putting Reuse Mechanisms to Work</h4><blockquote><strong>Inheritance versus Composition</strong></blockquote><p>The two most common techniques for reusing functionality in object-oriented systems are class inheritance and<strong> object composition</strong>. As I’ve explained, class inheritance lets you define the implementation of one class in terms of another’s. Reuse by subclassing is often referred to as <strong>white-box reuse.</strong></p><p>Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or <em>composing</em> objects to get more complex functionality. Object composition requires that the objects being composed have well-defined interfaces. This style of reuse is called <strong>black-box reuse</strong>, because no internal details of objects are visible.</p><p>Inheritance and composition each have their advantages and disadvantages. Class inheritance is defined statically at compile-time. It also make it easier to modify the implementation being reused. But you can’t change the implementations inherit from parent classes at run-time, because inheritance is defined at compile-time. The implementation of a subclass becomes so bound up with the implementation of its parent class that any change in the parent’s implementation will force the subclass to change.</p><p>Object composition is defined dynamically at run-time through objects acquiring references to other objects. Composition requires objects to respect each others’ interfaces. Objects are accessed solely through their interfaces, we don’t break encapsulation. Any object can be replaced at run-time by another as long as it has the same type.</p><p>Favoring object composition over class inheritance helps you keep each class encapsulated and focused on one task. Your classes and class hierarchies will remain small. On the other hand, a design based on object composition will have more objects.</p><blockquote><strong>Delegation</strong></blockquote><p><strong>Delegation </strong>is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, <em>two </em>objects are involved in handling a request: a receiving object delegates operations to its <strong>delegate.</strong></p><p>Differs from inheritance because it is no longer accessed via <em>this </em>or <em>self. </em>For example, instead of making class Window a subclass of Rectangle, the Window class might reuse the behavior of Rectangle by keeping a Rectangle instance variable and <em>delegating </em>Rectangle-specific behavior to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*a17-Ypm6j8gEcPOMFLAxvg.png" /></figure><p>The main advantage of delegation is that it make it easy to compose behaviors at run-time and to change the way they are composed. If we want, our window can become a circular at run-time, assuming Rectangle and Circle have the same type.</p><p>Delegation has a disadvantage it shares with other techniques that make software more flexible through object composition: Dynamic, highly parameterized software is harder to understand than more static software.</p><p>Several design pattern use delegation. The State, Strategy, and Visitor patterns depend on it.</p><blockquote>Inheritance versus Parameterized Types</blockquote><p>Another (not strictly object-oriented) technique for reusing functionality is through <strong>parameterized types</strong>, also known as <strong>generics</strong> and <strong>templates.</strong> This technique lets you define a type without specifying all the other types it uses.</p><p>Parameterized types give us a third way (in addition to class inheritance and object composition) to compose behavior in object-oriented systems. Many designs can be implemented using any of these three techniques.</p><p>There are important differences between these techniques. Object composition lets you change the behavior being composed atrun-time, but it also requires indirection and can be less efficient. Inheritance lets you provide default implementations for operations and lets subclasses override them. Parameterized typeslet you change the types that a class can use. But neither inheritance nor parameterized types can change at run-time.</p><h4>Relating Run-Time and Compile-Time Structures</h4><p>Consider the distinction between object <strong>aggregation</strong> and <strong>acquaintance</strong> and how differently they manifest themselves at compile- and run-times. Aggregation implies that one object owns or is responsible for another object. Generally we speak of an object having or being part of another object.</p><p>Acquaintance implies that an object merely knows of another object. Sometimes acquaintance is called “association” or the “using” relationship. Acquainted objects may request operations of each other, but they aren’t responsible for each other.</p><p>In this diagrams, a plain arrowhead line denotes acquaintance. An arrowhead line with a diamond at its base denotes aggregation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*8qTb7fN1IRAxC2nrfeB90Q.png" /></figure><h4>Designing for Change</h4><p>The key to maximizing reuse lies in anticipating new requirements and changes to existing requirements, and in designing your systems so that they can evolve accordingly.</p><p>Design patterns help you avoid this by ensuring that a system can change in specific ways.</p><p>There are some common causes of redesign along with the design pattern(s) that address them:</p><ul><li><em>Creating an object by specifying a class explicitly. </em>Specifying a class name when you create an object commits you a particular implementation instead of a particular interface. Design patterns: Abstract Factory, Factory Method, Prototype.</li><li><em>Dependence on specific operations. </em>When you specify a particular operation, you commit to one way of satisfying a request. By avoiding hard-coded request, you make it easier to change the way a request gets satisfied both at compiled-time and run-time. Design patterns: Chain of Responsibility, Command.</li><li><em>Algorithmic dependencies. </em>Algorithms are often extended, optimized, and replaced during development and reuse. Object that depend on an algorithm will have to change when the algorithm changes. Therefore algorithms that are likely to change should be isolated. Design patterns: Builder, Iterator, Strategy, Template Method, Visitor.</li><li><em>Tight coupling. </em>Tight coupling leads to monolithic systems, where you can’t change or remove a class without understanding and changing many other classes. The system becomes a dense mass that’s hard to learn, port, and maintain. Design patterns use techniques such as abstract coupling and layering to promote loosely coupled systems. Design patterns: Abstract Factory, Bridge, Chain of Responsibility, Command, Facade, Mediator, Observer.</li><li><em>Extending functionality by subclassing. </em>Customizing an object by subclassing often isn’t easy. Every new class has a fixed implementation overhead. Defining a subclass also requires an in-depth understanding of the parent class. Object composition in general and delegation in particular provide flexible alternatives to inheritance for combining behavior. New functionality can be added to an application by composing existing objects in new ways rather than by defining new subclasses of existing classes. Design patterns: Bridge, Chain of Responsibility, Composite, Decorator, Observer, Strategy.</li></ul><p><em>Originally published at </em><a href="https://federicobruzzone.github.io/post/design-patterns/design-patterns-introduction/"><em>https://federicobruzzone.github.io</em></a><em> on December 19, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f12fd2c7c92" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/design-patterns-introduction-6f12fd2c7c92">Design Patterns  —  Introduction</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>