<?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 Yevhen Baranov on Medium]]></title>
        <description><![CDATA[Stories by Yevhen Baranov on Medium]]></description>
        <link>https://medium.com/@baranoffei?source=rss-a7de86d5a087------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GsVXpeg2efVWzrRq5KM_LA.jpeg</url>
            <title>Stories by Yevhen Baranov on Medium</title>
            <link>https://medium.com/@baranoffei?source=rss-a7de86d5a087------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:54:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baranoffei/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[Angular’s GoF patterns. Abstract factory]]></title>
            <link>https://medium.com/@baranoffei/angulars-gof-patterns-abstract-factory-b24914b5e13d?source=rss-a7de86d5a087------2</link>
            <guid isPermaLink="false">https://medium.com/p/b24914b5e13d</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yevhen Baranov]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 10:49:26 GMT</pubDate>
            <atom:updated>2024-03-15T10:49:26.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dW3UyCw3rhZsrA_8vNd4RA.jpeg" /></figure><h3>Explaining the Abstract Factory Pattern and Its Primary Goal</h3><p><strong>The Abstract Factory pattern </strong>provides an interface for creating families of related objects without specifying their concrete classes.</p><p>Its <strong>main goal is to abstract object creation based on context, promoting flexibility and separation of concerns</strong>.</p><p>By encapsulating the creation logic, <strong>Abstract Factories shield client code from implementation details, allowing seamless transitions between different sets of related objects</strong>. This promotes code reusability and maintainability, making it a valuable tool in software development</p><h3>Key Features:</h3><ul><li><strong>Abstraction of Object Creation:</strong> Abstract Factory pattern abstracts the creation of families of related objects, allowing clients to work with these objects without specifying their concrete classes.</li><li><strong>Contextual Object Creation:</strong> Facilitates the creation of objects based on context or configuration, promoting flexibility in object instantiation.</li><li><strong>Dependency Injection Integration: </strong>Seamlessly integrates with Angular’s Dependency Injection mechanism to provide interfaces for creating sets of related services or components.</li><li><strong>Modular and Flexible: </strong>Enables dynamic instantiation of objects tailored to specific requirements, enhancing modularity and flexibility in Angular applications.</li><li><strong>Simplified Transition between Object Sets: </strong>Abstract Factories shield client code from implementation details, enabling seamless transitions between different sets of related objects without modifications.</li><li><strong>Promotes Reusability and Maintainability: </strong>Encourages code reusability, maintainability, and scalability by abstracting object creation logic and promoting separation of concerns in Angular projects.</li></ul><h3>Advantages:</h3><ul><li><strong>Centralized Control over Object Families: </strong>Abstract Factory ensures centralized control over the creation of families of related objects, simplifying state management in the application.</li><li><strong>Resource Efficiency:</strong> By abstracting the creation of related objects, Abstract Factory contributes to saving memory and system resources, as only necessary objects are instantiated based on contextual conditions.</li><li><strong>Enhanced Flexibility: </strong>Offers flexibility in object instantiation by allowing subclasses to create their instances within the factory hierarchy, promoting code extensibility and adaptability.</li><li><strong>Reduced Dependencies: </strong>Abstract Factory reduces direct dependencies between client code and concrete implementations, making it easier to introduce new types of products without impacting existing code. This enhances code modularity and simplifies testing and maintenance processes.</li><li><strong>Dynamic Configuration: </strong>Enables dynamic system configuration by facilitating the creation of objects based on runtime conditions or configurations, enhancing the system’s adaptability to changing requirements.</li><li><strong>Simplified Object Creation Process: </strong>Abstract Factory simplifies the object creation process by abstracting complex instantiation logic, promoting clean and modular code design.</li></ul><h3>Disadvantages</h3><ul><li><strong>Increased Complexity in Testing: </strong>Abstract Factory can complicate unit testing, as replacing abstract factory objects with mocks or stubs may be challenging, leading to more complex testing setups.</li><li><strong>Potential Hidden Dependencies:</strong> Injecting abstract factory instances can introduce hidden dependencies between components, potentially making the codebase harder to understand and debug.</li><li><strong>Scalability Challenges: </strong>In environments with concurrency or distributed systems, Abstract Factory may encounter synchronization and scalability issues, especially when managing the instantiation of complex object families.</li><li><strong>Risk of Violating SOLID Principles: </strong>Abstract Factory implementations may inadvertently violate the Single Responsibility Principle by adding additional responsibilities for managing object creation and configuration within the factory hierarchy, potentially leading to code maintenance challenges.</li></ul><h3>Code example</h3><p>Let’s say you have an admin panel and a user interface in your application, each with its own set of functionality and modules. <strong>You can use an abstract factory to create and load the appropriate modules as needed.</strong></p><p>For example, when switching between the administrative and user parts of the application.</p><p>The abstract class NgModuleFactory in Angular is used for the dynamic construction and initialization of modules, but it is marked as deprecated in the context of the new Ivy architecture.</p><p>NgModuleFactory in Angular is a powerful tool for managing modules and their loading at runtime, implemented using the Abstract Factory pattern. This presents an excellent opportunity for us to see how the creators of the framework implement this approach.</p><h4>Angular NgModuleFactory declaration</h4><pre>//@angular/core/index.d.ts<br>/**<br> * @publicApi<br> *<br> * @deprecated<br> * This class was mostly used as a part of ViewEngine-based JIT API and is no longer needed in Ivy<br> * JIT mode. See [JIT API changes due to ViewEngine deprecation](guide/deprecations#jit-api-changes)<br> * for additional context. Angular provides APIs that accept NgModule classes directly (such as<br> * [PlatformRef.bootstrapModule](api/core/PlatformRef#bootstrapModule) and<br> * [createNgModule](api/core/createNgModule)), consider switching to those APIs instead of<br> * using factory-based ones.<br> */<br>export declare abstract class NgModuleFactory&lt;T&gt; {<br>    abstract get moduleType(): Type&lt;T&gt;;<br>    abstract create(parentInjector: Injector | null): NgModuleRef&lt;T&gt;;<br>}</pre><p>abstract get moduleType(): Type&lt;T&gt;An abstract getter without implementation. It should return the type (class) of the module that the factory can create. This allows determining exactly which module will be constructed.<br>abstract create(parentInjector: <strong>Injector</strong> | null): <strong>NgModuleRef</strong>&lt;T&gt;- An abstract method that must be implemented to create an instance of the module. It accepts a parent dependency injector (or null) and returns a reference to the created module, allowing interaction with it after initialization.</p><h4>Angular NgModuleRef declaration</h4><pre>/**<br> * Represents an instance of an `NgModule` created by an `NgModuleFactory`.<br> * Provides access to the `NgModule` instance and related objects.<br> *<br> * @publicApi<br> */<br>export declare abstract class NgModuleRef&lt;T&gt; {<br>    /**<br>     * The injector that contains all of the providers of the `NgModule`.<br>     */<br>    abstract get injector(): EnvironmentInjector;<br>    /**<br>     * The resolver that can retrieve component factories in a context of this module.<br>     *<br>     * Note: since v13, dynamic component creation via<br>     * [`ViewContainerRef.createComponent`](api/core/ViewContainerRef#createComponent)<br>     * does **not** require resolving component factory: component class can be used directly.<br>     *<br>     * @deprecated Angular no longer requires Component factories. Please use other APIs where<br>     *     Component class can be used directly.<br>     */<br>    abstract get componentFactoryResolver(): ComponentFactoryResolver;<br>    /**<br>     * The `NgModule` instance.<br>     */<br>    abstract get instance(): T;<br>    /**<br>     * Destroys the module instance and all of the data structures associated with it.<br>     */<br>    abstract destroy(): void;<br>    /**<br>     * Registers a callback to be executed when the module is destroyed.<br>     */<br>    abstract onDestroy(callback: () =&gt; void): void;<br>}</pre><h4><strong>Angular Ingector declaration</strong></h4><pre>export declare abstract class Injector {<br>    static THROW_IF_NOT_FOUND: {};<br>    static NULL: Injector;<br>    /**<br>     * Internal note on the `options?: InjectOptions|InjectFlags` override of the `get`<br>     * method: consider dropping the `InjectFlags` part in one of the major versions.<br>     * It can **not** be done in minor/patch, since it&#39;s breaking for custom injectors<br>     * that only implement the old `InjectorFlags` interface.<br>     */<br>    /**<br>     * Retrieves an instance from the injector based on the provided token.<br>     * @returns The instance from the injector if defined, otherwise the `notFoundValue`.<br>     * @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.<br>     */<br>    abstract get&lt;T&gt;(token: ProviderToken&lt;T&gt;, notFoundValue: undefined, options: InjectOptions &amp; {<br>        optional?: false;<br>    }): T;<br>    /**<br>     * Retrieves an instance from the injector based on the provided token.<br>     * @returns The instance from the injector if defined, otherwise the `notFoundValue`.<br>     * @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.<br>     */<br>    abstract get&lt;T&gt;(token: ProviderToken&lt;T&gt;, notFoundValue: null | undefined, options: InjectOptions): T | null;<br>    /**<br>     * Retrieves an instance from the injector based on the provided token.<br>     * @returns The instance from the injector if defined, otherwise the `notFoundValue`.<br>     * @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.<br>     */<br>    abstract get&lt;T&gt;(token: ProviderToken&lt;T&gt;, notFoundValue?: T, options?: InjectOptions | InjectFlags): T;<br>    /**<br>     * Retrieves an instance from the injector based on the provided token.<br>     * @returns The instance from the injector if defined, otherwise the `notFoundValue`.<br>     * @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.<br>     * @deprecated use object-based flags (`InjectOptions`) instead.<br>     */<br>    abstract get&lt;T&gt;(token: ProviderToken&lt;T&gt;, notFoundValue?: T, flags?: InjectFlags): T;<br>    /**<br>     * @deprecated from v4.0.0 use ProviderToken&lt;T&gt;<br>     * @suppress {duplicate}<br>     */<br>    abstract get(token: any, notFoundValue?: any): any;<br>    /**<br>     * @deprecated from v5 use the new signature Injector.create(options)<br>     */<br>    static create(providers: StaticProvider[], parent?: Injector): Injector;<br>    /**<br>     * Creates a new injector instance that provides one or more dependencies,<br>     * according to a given type or types of `StaticProvider`.<br>     *<br>     * @param options An object with the following properties:<br>     * * `providers`: An array of providers of the [StaticProvider type](api/core/StaticProvider).<br>     * * `parent`: (optional) A parent injector.<br>     * * `name`: (optional) A developer-defined identifying name for the new injector.<br>     *<br>     * @returns The new injector instance.<br>     *<br>     */<br>    static create(options: {<br>        providers: StaticProvider[];<br>        parent?: Injector;<br>        name?: string;<br>    }): Injector;<br>    /** @nocollapse */<br>    static ɵprov: unknown;<br>}</pre><h4>Step 1. Create an interface for our abstract module factory</h4><p>Okay, now is the perfect time to start writing our code.<br>Let’s define AbstractModulesFactory&lt;T&gt;, an interface for asynchronous creation of Angular module factories.</p><pre>// abstract-module.factory.ts<br>import { NgModuleFactory } from &#39;@angular/core&#39;;<br><br>export interface AbstractModulesFactory&lt;T&gt; {<br>  createModuleFactory(): Promise&lt;NgModuleFactory&lt;T&gt;&gt;;<br>}</pre><h4>Step 2. Create AppModulesFactoryImpl service</h4><p>This code defines a service called AppModulesFactoryImpl responsible for dynamically loading Angular modules. It asynchronously loads the specified module, returning its factory. Any errors encountered during the process are logged and thrown for handling.</p><pre>// module-factory.service.ts<br>import { Injectable, NgModuleFactory, SystemJsNgModuleLoader } from &#39;@angular/core&#39;;<br>import { AbstractModulesFactory } from &#39;./abstract-module.factory&#39;;<br><br>// AppModulesFactoryImpl service is used to dynamically load Angular modules.<br>@Injectable()<br>export class AppModulesFactoryImpl&lt;T&gt; implements AbstractModulesFactory&lt;T&gt; {<br><br>   // defines service dependencies: SystemJsNgModuleLoader for loading modules<br>   constructor(<br>      private loader: SystemJsNgModuleLoader, <br>      private modulePath: string<br>   ) {}<br><br>   // method for loading a module and creating its factory.<br>   async createModuleFactory(): Promise&lt;NgModuleFactory&lt;T&gt;&gt; {<br>     try {<br>       const module = await this.loader.load(this.modulePath);<br>       if (module instanceof NgModuleFactory) {<br>         return module;<br>       } else {<br>         return await this.loader.compile(module);<br>       }<br>     } catch (error) {<br>       console.error(`Failed to load module &#39;${this.modulePath}&#39;`, error);<br>       throw error;<br>     }<br>   }<br>}</pre><h4>Step 3. Create Admin module.</h4><p>AdminModule is an Angular module for app administration, containing components and services for tasks like user management and settings. It ensures clean code organization and scalability.</p><pre>// admin/admin.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { AdminComponent } from &#39;./admin.component&#39;;<br>import { AdminService } from &#39;./admin.service&#39;;<br><br>@NgModule({<br>  declarations: [AdminComponent],<br>  imports: [CommonModule],<br>  providers: [AdminService],<br>})<br>export class AdminModule {}</pre><h4><strong>Step 4. Create User module</strong></h4><p>UserModule is an Angular module dedicated to user-related functionality in the application. It comprises components and services for tasks like user profiles and interactions. This module ensures clear code organization and scalability.</p><pre>// user/user.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { UserComponent } from &#39;./user.component&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@NgModule({<br>  declarations: [UserComponent],<br>  imports: [CommonModule],<br>  providers: [UserService],<br>})<br>export class UserModule {}</pre><h4><strong>Step 5. Create a main page</strong></h4><p>This code creates the main page in the Angular application.</p><p>It dynamically loads admin and user modules when the corresponding buttons are clicked. Users will see a welcome message and can switch between the administrative and user parts of the application.</p><pre>// app.component.ts<br>import { Component, NgModuleFactoryLoader, Type, OnInit } from &#39;@angular/core&#39;;<br>import { AbstractModulesFactory } from &#39;./abstract-module.factory&#39;;<br>import { AdminModule } from &#39;./admin/admin.module&#39;;<br>import { UserModule } from &#39;./user/user.module&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.compomemt.html&#39;,<br>})<br>export class AppComponent implements OnInit {<br>  loadedModule: Type&lt;any&gt;;<br>  loadedModuleName: string;<br><br>  constructor(<br>    private moduleLoader: NgModuleFactoryLoader,<br>    private adminModulesFactory: AbstractModulesFactory&lt;AdminModule&gt;,<br>    private userModulesFactory: AbstractModulesFactory&lt;UserModule&gt;<br>  ) {}<br><br>  ngOnInit(): void {<br>    // Load default module on initialization<br>    this.loadModule(this.adminModulesFactory, &#39;AdminModule&#39;);<br>  }<br><br>  async loadModule&lt;T&gt;(factory: AbstractModulesFactory&lt;T&gt;, moduleName: string): Promise&lt;void&gt; {<br>    try {<br>      const moduleFactory = await factory.createModuleFactory();<br>      this.loadedModule = this.moduleLoader.create(moduleFactory).instance;<br>      this.loadedModuleName = moduleName;<br>    } catch (error) {<br>      console.error(`Failed to load ${moduleName}`, error);<br>    }<br>  }<br>}</pre><pre>&lt;!-- app.component.html --&gt;<br>&lt;h1&gt;Welcome to the SUPER APP!&lt;/h1&gt;<br><br>&lt;button (click)=&quot;loadModule(adminModulesFactory, &#39;AdminModule&#39;)&quot;&gt;<br>  Load ADMIN Module<br>&lt;/button&gt;<br>&lt;button (click)=&quot;loadModule(userModulesFactory, &#39;UserModule&#39;)&quot;&gt;<br>  Load USER Module<br>&lt;/button&gt;<br><br>&lt;div *ngIf=&quot;loadedModuleName&quot;&gt;<br>  &lt;h2&gt;{{ loadedModuleName }}&lt;/h2&gt;<br>  &lt;ng-container *ngComponentOutlet=&quot;loadedModule&quot;&gt;&lt;/ng-container&gt;<br>&lt;/div&gt;</pre><h3>Examples of Abstract Factory Usage in Angular:</h3><ul><li>LazyLoadedModuleFactoryLoader (<strong>DEPRECATED</strong> )</li><li>NgModuleFactory</li><li>ComponentFactoryResolver (<strong>DEPRECATED</strong>)</li><li>HttpClientTestingModule</li></ul><h3>When should you use the Abstract Factory pattern in Angular?</h3><ul><li>When you need to <strong>create families of related objects or products with a shared purpose </strong>throughout your Angular application’s lifecycle.</li><li>When you <strong>require a unified interface for creating sets of related objects without revealing their concrete implementations</strong>, thus enhancing modularity and flexibility.</li><li><strong>If</strong> your <strong>codebase necessitates dynamic instantiation of objects based on contextual conditions or configurations</strong>, enabling seamless transitions between different sets of related objects.</li><li>When <strong>reducing dependencies between client code and concrete implementations is desired</strong>, facilitating the introduction of new types of products or services without disrupting existing code.</li><li>If you aim to <strong>improve code reusability, maintainability, and scalability by abstracting object creation logic and promoting separation</strong> of concerns within your Angular projects.</li></ul><p>If you found this topic interesting and want to deepen your knowledge in the area of design patterns, be sure to check out my other articles on this subject.<br><strong>Creational Design Patterns:</strong></p><ul><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-singleton-98f491c9dad0">Angular’s GoF patterns. Singleton.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-factory-method-0c740fbd3b2e">Angular’s GoF patterns. Factory Method.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-prototype-01082fe5609e">Angular’s GoF patterns. Prototype.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-builder-75c0a4f50dac">Angular’s GoF patterns. Builder.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b24914b5e13d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular’s GoF patterns. Builder.]]></title>
            <link>https://medium.com/@baranoffei/angulars-gof-patterns-builder-75c0a4f50dac?source=rss-a7de86d5a087------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c0a4f50dac</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Yevhen Baranov]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 11:32:30 GMT</pubDate>
            <atom:updated>2024-03-07T11:32:30.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozZ7t3_aG9i7qG-Bu6DYqg.jpeg" /></figure><h3>Explaining the BuilderPattern and Its Primary Goal</h3><p>The Builder pattern in software design <strong>helps construct complex objects by separating their construction from their representation</strong>.</p><p>This allows for different representations using the same construction process.</p><p><strong>The main goal </strong>is to enhance object c<strong>reation flexibility, allowing for easier management and modification</strong>.</p><p>By using a dedicated Builder object-directed by a Director, this pattern simplifies the <strong>creation of complex objects, promoting modular, maintainable code</strong>. It addresses issues associated with numerous object configurations, supporting clearer, more adaptable code structures.</p><h3>Key Features:</h3><p>- <strong>Separation of Construction and Representation:</strong> Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different results.<br><strong>- Step-by-Step Construction: </strong>Enables building objects step-by-step, under control of the director class.<br><strong>- Flexibility in Object Construction: </strong>Provides greater control over the construction process compared to other creational patterns.<br><strong>- Reusability: </strong>The builder can be reused to build variations of the product.</p><h4>Advantages:</h4><p><strong>- Improved Control:</strong> Allows for more precise control over the construction process than other creational patterns.<br><strong>- Encapsulation and Isolation:</strong> Encapsulates the construction code and exposes only what is necessary, leading to cleaner, more readable code.<br><strong>- Flexibility:</strong> Users can construct complex objects step by step or reuse the same construction process for different types of objects.<br><strong>- Scalability:</strong> Easier to scale and modify the construction process without affecting the end product’s class.</p><h4>Disadvantages:</h4><ul><li><strong>Complexity:</strong> Can add unnecessary complexity to the code if the underlying process being abstracted is not sufficiently complex.<br><strong>- Increased Object Count: </strong>May lead to an increased number of smaller classes, making the code more fragmented.<br><strong>- Indirect Code Relationship: </strong>The link between the director and the builder might make the code harder to understand.<br><strong>- Initialization Overhead:</strong> Builders can introduce an overhead in the initialization process.</li></ul><h4>Code Example: Building a Product Card Component with the Builder Pattern in Angular</h4><p>Let’s develop an example of a customizable product card component using the Builder pattern in Angular.</p><p><strong>Step 1: Define Product Model Interface:</strong></p><p>The product model is a simple TypeScript interface that outlines the structure of a product object. It defines the properties that each product should have, such as id, name, price, and optionally description and imageUrl.</p><pre>// product.model.ts<br>export interface Product {<br>  id: number;<br>  name: string;<br>  price: number;<br>  description?: string;<br>  imageUrl?: string;<br>}</pre><p><strong>Step 2: Define ProductCardBuilder Interface:</strong></p><p>This interface defines the methods required for building a product card component. It follows the Builder pattern, allowing for the step-by-step construction of a ProductCardComponent by setting different product attributes.</p><pre>// product-card-builder.interface.ts<br>export interface ProductCardBuilder {<br>  setName(name: string): ProductCardBuilder;<br>  setPrice(price: number): ProductCardBuilder;<br>  setDescription(description: string): ProductCardBuilder;<br>  setImageUrl(imageUrl: string): ProductCardBuilder;<br>  build(): ProductCardComponent;<br>}</pre><p><strong>Step 3: Implement the Product Card Component:</strong></p><p>This component is responsible for displaying the product information in the UI. It takes a Product object and displays its properties such as name, price, description, and image.</p><pre>// product-card.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { Product } from &#39;./product.model&#39;;<br><br>@Component({<br>  selector: &#39;app-product-card&#39;,<br>  templateUrl: &#39;./product-card.component.html&#39;,<br>})<br>export class ProductCardComponent {<br>  product: Product;<br>  constructor() {}<br><br>  setProduct(product: Product): void {<br>    this.product = product;<br>  }<br>}</pre><p><strong>Step 4: Implement the ProductCardBuilder :</strong></p><p>This is the builder class used to step-by-step construct a ProductCardComponent. It implements the ProductCardBuilder interface, allowing for the fluent setting of product attributes before building the final component.</p><pre>// card.builder.ts<br>import { Product, ProductCardBuilder } from &#39;./product.model&#39;;<br>import { ProductCardComponent } from &#39;./product-card.component&#39;;<br><br>export class CardBuilder implements ProductCardBuilder {<br>  private product: Product = { id: 0, name: &#39;&#39;, price: 0 };<br><br>  setName(name: string): CardBuilder {<br>    this.product.name = name;<br>    return this;<br>  }<br><br>  setPrice(price: number): CardBuilder {<br>    this.product.price = price;<br>    return this;<br>  }<br><br>  setDescription(description: string): CardBuilder {<br>    this.product.description = description;<br>    return this;<br>  }<br><br>  setImageUrl(imageUrl: string): CardBuilder {<br>    this.product.imageUrl = imageUrl;<br>    return this;<br>  }<br><br>  build(): ProductCardComponent {<br>    const productCard = new ProducCardComponent();<br>    productCard.setProduct(this.product);<br>    return productCard;<br>  }<br>}</pre><p><strong>Explanation: </strong>The CardBuilder class facilitates the construction of a ProductCardComponent by providing a fluent API to set various product properties. This builder pattern implementation helps in maintaining clean and readable code, especially when dealing with complex objects that require various attributes to be set before instantiation.</p><p>It follows the builder pattern&#39;s standard structure, allowing for incremental setting of properties and culminating in the creation of a fully initialized ProductListComponent instance.</p><p><strong>Step 5: Create Product List Component:</strong></p><p>This component will display an array of product cards, each created using the CardBuilder.</p><pre>// product-list.component.ts:<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { CardBuilder } from &#39;./card.builder&#39;;<br>import { ProductCardComponent } from &#39;./product-card.component&#39;;<br><br>@Component({<br>  selector: &#39;app-product-list&#39;,<br>  templateUrl: &#39;./product-list.component.html&#39;,<br>  styleUrls: [&#39;./product-list.component.css&#39;]<br>})<br>export class ProductListComponent implements OnInit {<br>  productCards: ProductCardComponent[] = []; // Array to store product card components<br><br>  constructor() {}<br><br>  ngOnInit(): void {<br>    // Create product cards using the Builder and add them to the array<br>    const productCardBuilder = new ConcreteProductCardBuilder();<br>    <br>    // Example of creating several products<br>    const products = [<br>      { name: &#39;Awesome Product&#39;, price: 19.99, description: &#39;This is an awesome product.&#39;, imageUrl: &#39;path/to/image1.jpg&#39; },<br>      { name: &#39;Another Great Product&#39;, price: 29.99, description: &#39;This is another great product.&#39;, imageUrl: &#39;path/to/image2.jpg&#39; },<br>      // Add more products as needed<br>    ];<br><br>    products.forEach(product =&gt; {<br>      const productCard = productCardBuilder<br>        .setName(product.name)<br>        .setPrice(product.price)<br>        .setDescription(product.description)<br>        .setImageUrl(product.imageUrl)<br>        .build();<br>      this.productCards.push(productCard);<br>    });<br>  }<br>}</pre><pre>&lt;!-- product-list.component.html --&gt;<br>&lt;div class=&quot;product-list&quot;&gt;<br>  &lt;!-- Display the product cards --&gt;<br>  &lt;div *ngFor=&quot;let productCard of productCards&quot;&gt;<br>    &lt;!-- You can insert the content of the card directly here or use other Angular mechanisms to display components --&gt;<br>    &lt;app-product-card [product]=&quot;productCard.product&quot;&gt;&lt;/app-product-card&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><h3>Examples of Builder Usage in Angular:</h3><p>The Builder pattern is not directly associated with specific parts of the Angular source code, mainly because Angular is a framework focused on the component approach and dependency injection for managing objects and their lifecycle.</p><p>However, the concepts and ideas underlying the Builder pattern can be seen in various aspects of Angular.</p><p><strong>The Reactive Forms system in Angular demonstrates ideas similar to the Builder pattern</strong>, allowing developers to incrementally create complex forms using a programmatic API.</p><p>The <strong>FormControl</strong>, <strong>FormGroup</strong>, and <strong>FormArray</strong> methods are <strong>used to build the form structure, reminiscent of the ‘building’ process </strong>of an object.</p><pre>const form = new FormGroup({<br>  firstName: new FormControl(&#39;&#39;, Validators.required),<br>  lastName: new FormControl(&#39;&#39;, Validators.required),<br>  address: new FormGroup({<br>    street: new FormControl(&#39;&#39;),<br>    city: new FormControl(&#39;&#39;)<br>  })<br>});</pre><h4>When should you use the Builder pattern in Angular?</h4><p>The Builder pattern should be considered in Angular applications when:</p><p>1. You need to <strong>construct complex objects step by step</strong>, and these objects are composed of many interrelated parts or layers. This is common in cases where different configurations of an object are needed depending on the context of the application.</p><p>2. You want to <strong>isolate the construction of a complex object from its representation</strong>, allowing the same construction process to create different representations. This can be particularly useful in a dynamic Angular application where the final object might vary significantly based on user input or other runtime conditions.</p><p>3. The construction process of <strong>an object must allow different representations to be constructed under different circumstances</strong>. This flexibility is crucial for developing scalable and maintainable Angular applications, especially when dealing with complex form inputs or dynamic component rendering.</p><p>4. You aim to <strong>encapsulate the code that assembles complex objects</strong> to make the Angular application cleaner and more modular. This encapsulation helps in reducing dependencies and makes unit testing easier, as the construction logic is separated from the business logic.</p><p>If you found this topic interesting and want to deepen your knowledge in the area of design patterns, be sure to check out my other articles on this subject.<br><strong>Creational Design Patterns:</strong></p><ul><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-singleton-98f491c9dad0">Angular’s GoF patterns. Singleton.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-factory-method-0c740fbd3b2e">Angular’s GoF patterns. Factory Method.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-prototype-01082fe5609e">Angular’s GoF patterns. Prototype.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c0a4f50dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular’s GoF patterns. Prototype.]]></title>
            <link>https://medium.com/@baranoffei/angulars-gof-patterns-prototype-01082fe5609e?source=rss-a7de86d5a087------2</link>
            <guid isPermaLink="false">https://medium.com/p/01082fe5609e</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[prototype-pattern]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yevhen Baranov]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 11:16:26 GMT</pubDate>
            <atom:updated>2024-02-29T11:16:26.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cr0NzM5UQvCjmMSN2vGWVg.jpeg" /></figure><h3>Explaining the Prototype Pattern and Its Primary Goal</h3><p><strong>The Prototype pattern</strong> in software development helps avoid the traditional object creation overhead (via the new keyword) by enabling efficient instance copying. Its <strong>main goal is to allow objects to replicate themselves, simplifying the creation process</strong>.</p><p>Instead of starting from scratch, objects can be cloned and adapted as needed. <strong>This approach supports</strong> the dynamic addition of new types, fosters <strong>loose coupling</strong>, and <strong>improves scalability</strong>.</p><p>Essentially, the Prototype pattern is ideal for creating similar objects efficiently, promoting system flexibility and adaptability by leveraging cloning.</p><h3>Key Features:</h3><ul><li><strong>Cloning:</strong> Prototype allows creating an object based on a template instance through cloning, avoiding the costly process of new instance creation.</li><li><strong>Customization: </strong>Once cloned, the new instances can be customized for specific needs, which provides flexibility in object creation.</li><li><strong>Avoiding complex creation:</strong> Helps in avoiding the complexity of creating objects when the process involves many steps or requires an extensive amount of resources.</li><li><strong>Reduced subclassing</strong>: Prototype can reduce the need for subclassing, as object behavior can be configured at runtime via composition or through cloning pre-existing designs.</li><li><strong>Adding and removing objects at runtime</strong>: Objects can be added or removed at runtime with Prototype, which can be particularly useful in dynamic environment applications.</li></ul><h3>Advantages:</h3><ul><li><strong>Efficiency</strong>: Cloning is generally more efficient than creating new objects, especially when dealing with complex object structures or resource-intensive processes.</li><li><strong>Flexibility in objects creation: </strong>Offers the flexibility to create complex objects without needing a class hierarchy of factories (unlike the Factory Method).</li><li><strong>Dynamic system configuration:</strong> Enables systems to be more dynamic, as objects can be configured and extended at runtime.</li><li><strong>Simplifies object creation</strong>: Reduces the need for creating similar but different classes, thus simplifying the object creation process.</li></ul><h3>Disadvantages:</h3><ul><li><strong>Complex object cloning:</strong> Cloning complex objects that have circular references or complex states can be difficult.</li><li><strong>Ambiguous cloning:</strong> It’s not always clear how deep the cloning process should go (shallow vs. deep copy).</li><li><strong>Hidden costs: </strong>While cloning might seem simple, it can have hidden costs in terms of processing, especially with deep cloning.</li><li><strong>Managing clones:</strong> Keeping track of all cloned objects and managing their lifecycle can become complex.</li><li><strong>Prototype initialization:</strong> Ensuring the prototype is correctly initialized and managing the prototype’s lifecycle can be challenging.</li><li><strong>Overuse</strong>: Overusing the Prototype pattern can lead to a system where the design becomes harder to understand due to an abundance of partially similar object configurations.</li></ul><h3>Code example</h3><p>Let’s look at a practical example where we can use the Prototype pattern in Angular, this time focusing on the scenario of <strong>creating a complex widget</strong> that the user can customize and add to a dashboard.</p><p>This example will show how we can use Prototype to dynamically create and customize components based on user preferences.</p><h4>Step 1: Defining the Base Interface</h4><p>First, we will define the CustomComponent interface, which will be implemented by all components that support cloning via the Prototype pattern. This interface will include the clone method, returning an instance of the component.</p><pre>//custom-component.interface.ts<br>export interface CustomComponent {<br>  clone(): CustomComponent;<br>}</pre><h4>Step 2: Defining the Base Component Class</h4><p>Then, we will create an abstract base class AbstractComponent that implements this interface.</p><pre>// abstract-component.component.ts<br>export abstract class AbstractComponent implements CustomComponent {<br>  abstract clone(): CustomComponent;<br>  <br>  // Common properties and methods for all components<br>}</pre><h4>Step 3: Implementing Concrete Components</h4><p>Let’s assume we have a DashboardComponent that we want to dynamically clone with different settings.</p><pre>// weather-widget.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { AbstractComponent } from &#39;./abstract.component&#39;;<br><br>@Component({<br>  template: `&lt;div&gt;Weather Widget Component Content&lt;/div&gt;`<br>})<br>export class WeatherWidgetComponent extends AbstractComponent {<br>  title: string;<br>  constructor() {<br>    super();<br>    this.title = &#39;Default Title&#39;;<br>  }<br><br>  setTitle(title: string) {<br>    this.title = title;<br>  }<br><br>  clone(): WeatherWidgetComponent {<br>    const clone = new WeatherWidgetComponent();<br>    clone.setTitle(this.title);<br>    // Additional settings can be added here<br>    return clone;<br>  }<br>}</pre><h4>Step 4: Dynamically Creating and Configuring Widgets</h4><p>Now we can use our WeatherWidgetComponent for dynamically creating and configuring widgets. Suppose the user can add and configure weather widgets for different locations on their dashboard.</p><pre>// dashboard.component.ts<br>import { Component, ViewChild, ViewContainerRef } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  template: `<br>    &lt;button (click)=&quot;addWeatherWidget(&#39;New York&#39;)&quot;&gt;Add New York Weather Widget&lt;/button&gt;<br>    &lt;div #widgetContainer&gt;&lt;/div&gt; &lt;!-- Used to display the widget itself --&gt;<br>  `,<br>})<br>export class DashboardComponent {<br> @ViewChild(&#39;widgetContainer&#39;, { read: ViewContainerRef }) container: ViewContainerRef;<br> title: string = &#39;Default Title&#39;;<br><br> constructor() {}<br><br> setTitle(title: string) {<br>  this.title = title;<br> }<br><br> addWeatherWidget(location: string) {<br>  // Since the component acts as both a dashboard and a widget, we can simply change its state<br>  this.setTitle(`Weather Widget for ${location}`);<br>  <br>  // Additional settings specific to the weather widget can be added here<br> }<br><br> // The clone method can be used if you still want to support cloning<br> clone(): DashboardComponent {<br>  <br>  // This is a demonstration, in practice cloning might be more complex<br>  const clone = new DashboardComponent(); <br>  <br>  // Add any other properties that need to be cloned<br>  clone.setTitle(this.title);<br>  return clone;<br> }<br>}</pre><h3>Examples of Prototype Usage in Angular:</h3><p>In Angular, there is <strong>NO direct use of the Prototype pattern</strong>, as seen with the Factory Method or Singleton patterns. The Prototype pattern involves creating new objects by copying existing instances.</p><p>In the context of Angular, this is not a standard practice.</p><p>Angular leans towards using a Dependency Injection system, which implies creating instances of services and components when needed, but not by copying from existing instances, rather by instantiating and configuring them according to the provided settings.</p><p><strong>In Angular, each component or service is created as a new instance</strong> when required and configured through mechanisms like providers, modules, and decorators.</p><p>This differs from <strong>the Prototype approach, where new objects are created by copying already existing ones</strong>.</p><p>Thus, although Angular uses various design patterns to solve standard development tasks, <strong>the direct use of the Prototype pattern under the hood of Angular is not characteristic</strong>.</p><h3>When should you use the Prototype pattern in Angular?</h3><ul><li>You need to <strong>create objects that are similar to an existing object</strong> or have a complex structure, <strong>and you want to avoid the costs</strong> associated with <strong>their initialization</strong>.</li><li>When <strong>creating a copy of an object is less resource-intensive than initializing it from scratch</strong>.</li><li>When the <strong>system must be independent of the ways objects are created, composed, and represented</strong>.</li><li>When <strong>variations of objects are required, but not their classes.</strong></li></ul><p>If you found this topic interesting and want to deepen your knowledge in the area of design patterns, be sure to check out my other articles on this subject.<br><strong>Creational Design Patterns:</strong></p><ul><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-singleton-98f491c9dad0">Angular’s GoF patterns. Singleton.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-factory-method-0c740fbd3b2e">Angular’s GoF patterns. Factory Method.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01082fe5609e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular’s GoF patterns. Factory Method.]]></title>
            <link>https://medium.com/@baranoffei/angulars-gof-patterns-factory-method-0c740fbd3b2e?source=rss-a7de86d5a087------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c740fbd3b2e</guid>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[factory-method]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Yevhen Baranov]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 11:15:40 GMT</pubDate>
            <atom:updated>2024-03-04T12:48:13.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM1GTfnP_1QYJRiX81Y0Zg.jpeg" /></figure><h3>Explaining the Factory Method Pattern and Its Primary Goal</h3><p>The Factory Method is a way to organize code that helps programs create objects not directly, but through a special function. This is useful when there are many different types of objects in the program, and the exact type of object that needs to be created depends on the situation.</p><p>The main purpose of this method is to provide a general way to create objects while allowing more specific versions of the program to change the type of objects that are created. This is great for situations when the program needs to create a certain type of object, but the exact type may vary. This approach makes the code more flexible and follows the rule that programs should be open to adding new features but not require changes for existing functions.</p><h3>Application in Angular</h3><p>In Angular, the <strong>Factory Method pattern is used for flexible service and component creation</strong>, allowing for various instances or configurations. This pattern is particularly beneficial when services require different settings based on external conditions or application configurations.</p><p>Utilized within Dependency Injection (DI), the Factory Method facilitates creating service instances with unique setups, promoting testing ease and code modularity. <strong>Angular implements this pattern through factory functions in providers</strong>, enabling dynamic service creation based on application needs, thus offering enhanced flexibility and control in object creation.</p><h3>Key Features:</h3><ul><li><strong>Abstracting creation:</strong> Factory Method separates object creation from usage, increasing flexibility in what and when objects are created.</li><li><strong>Delegating to subclasses:</strong> It lets subclasses decide which objects to create instead of using fixed classes, enhancing system flexibility.</li><li><strong>Supports SOLID: </strong>Mainly backs the <strong>open/closed principle</strong>, letting systems expand without needing changes.</li></ul><h3>Advantages:</h3><ul><li><strong>Flexibility and expandability:</strong> Allows for easy introduction of new types of products without changing existing code.</li><li><strong>Reducing dependencies: </strong>The Factory Method reduces the direct dependency between classes that create and use objects, making code modification and testing simpler.</li><li><strong>Ease of maintenance and updates: </strong>Code using the pattern is easier to maintain and update, as adding a new type of product often doesn’t require changes to the existing code that uses the factory.</li></ul><h3>Disadvantages</h3><ul><li><strong>Complex architecture:</strong> Using Factory Method can complicate application architecture, especially when used unnecessarily or in simple scenarios.</li><li><strong>Code bloat:</strong> Creating many factory methods and classes can overload the code, making it hard to understand, particularly for new developers.</li><li><strong>Performance issues:</strong> In some cases, particularly with incorrect implementation, Factory Method can affect application performance due to additional method calls and object creations.</li><li><strong>Debugging difficulty: </strong>Following this pattern can make debugging harder since the actual object creation is hidden within the factory method, complicating error tracking.</li><li><strong>Need for careful planning:</strong> Effective use of Factory Method requires detailed planning and understanding of when and what objects should be created. Planning errors can lead to incorrect or excessive implementation.</li><li><strong>Limited flexibility in some scenarios: </strong>While Factory Method provides flexibility in object creation, it can be limited in scenarios requiring very dynamic or conditional object creation.</li><li><strong>Not suitable for simple applications: </strong>For small or simple applications with a relatively static structure, using Factory Method might be unnecessary and complicate the project.</li></ul><h3>Code example</h3><p>Let’s design an example of a notification system using the Factory Method pattern in Angular.</p><p><strong>Step 1: Create Notification Framework:</strong></p><p>Set up the Notification interface specifying essential functions and message structure. Implement BaseNotification, an abstract class fulfilling this interface with common functionality and placeholders for specific display actions.</p><pre>// notification.interface.ts<br>export interface Notification {<br>    message: string;<br>    show(): void;<br>    hide(): void;<br>    update(message: string): void;<br>}</pre><pre>// base-notification.class.ts<br>import { Notification } from &#39;./notification.interface&#39;;<br><br>export abstract class BaseNotification implements Notification {<br>    constructor(public message: string) {}<br><br>    abstract show(): void;<br>    abstract hide(): void;<br><br>    update(message: string): void {<br>        this.message = message;<br>        console.log(&#39;Updated message:&#39;, this.message);<br>    }<br>}</pre><p><strong>Step 2: Develop Specific Notification Classes:</strong></p><p>Create SuccessNotification, WarningNotification, and ErrorNotification classes, each extending BaseNotification. Implement specific show() and hide() methods for different message types. Make them injectable for Angular&#39;s DI system.</p><pre>// success-notification.class.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { BaseNotification } from &#39;./base-notification.class&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class SuccessNotification extends BaseNotification {<br>    show(): void { console.log(&#39;Success:&#39;, this.message) }<br>    hide(): void { console.log(&#39;Hide Success notification&#39;) }<br>}</pre><pre>// warning-notification.class.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { BaseNotification } from &#39;./base-notification.class&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class WarningNotification extends BaseNotification {<br>    show(): void { console.log(&#39;Warning:&#39;, this.message) }<br>    hide(): void { console.log(&#39;Hide Warning notification&#39;) }<br>}</pre><pre>// error-notification.class.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { BaseNotification } from &#39;./base-notification.class&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class ErrorNotification extends BaseNotification {<br>    show(): void { console.log(&#39;Error:&#39;, this.message) }<br>    hide(): void { console.log(&#39;Hide Error notification&#39;) }<br>}</pre><p><strong>Step 3: Implement the Factory Service:</strong></p><p>Develop the NotificationFactory service. It uses Angular&#39;s injector to dynamically produce specific notification types—Success, Warning, or Error—based on input and initializes them with a message.</p><pre>// notification-factory.service.ts<br>import { Injectable, Injector } from &#39;@angular/core&#39;;<br>import { Notification, NotificationType } from &#39;./notification.interface&#39;;<br>import { SuccessNotification, WarningNotification, ErrorNotification } from &#39;./notifications&#39;;<br><br>@Injectable({<br>    providedIn: &#39;root&#39;<br>})<br>export class NotificationFactory {<br>  constructor(private injector: Injector) {}<br><br>  createNotification(type: NotificationType, message: string): Notification {<br>    switch (type) {<br>      case &#39;success&#39;:<br>        return this.injector.get(SuccessNotification).update(message);<br>      case &#39;warning&#39;:<br>        return this.injector.get(WarningNotification).update(message);<br>      case &#39;error&#39;:<br>        return this.injector.get(ErrorNotification).update(message);<br>      default:<br>        throw new Error(&#39;Unsupported notification type&#39;);<br>        }<br>    }<br>}</pre><p><strong>Step 4: Create Notification Service:</strong></p><p>Set up a NotificationService using Angular and RxJS to manage and emit notifications. It employs NotificationFactory for generating various notifications and updates subscribers through a BehaviorSubject.</p><pre>// notification.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { BehaviorSubject } from &#39;rxjs&#39;;<br>import { NotificationFactory } from &#39;./notification-factory.service&#39;;<br>import { NotificationType } from &#39;./notification.interface&#39;;<br><br>@Injectable({<br>    providedIn: &#39;root&#39;<br>})<br>export class NotificationService {<br> private notificationSource = new BehaviorSubject&lt;Notification | null&gt;(null);<br> public notifications = this.notificationSource.asObservable();<br><br> constructor(private notificationFactory: NotificationFactory) {}<br><br> showNotification(type: NotificationType, message: string): void {<br>   const notification = this.notificationFactory.createNotification(type, message);<br>   this.notificationSource.next(notification);<br> }<br>}</pre><p><strong>Step 5: Create Notification Display Component:</strong></p><p>Make NotificationComponent to show notifications. It subscribes to NotificationService for updates and displays them. It subscribes on initialization and unsubscribes on destruction. The HTML template shows notifications if they exist, styled with CSS.</p><pre>// notification.component.ts<br>import { Component, OnInit, OnDestroy } from &#39;@angular/core&#39;;<br>import { Subscription } from &#39;rxjs&#39;;<br>import { NotificationService } from &#39;./notification.service&#39;;<br>import { Notification } from &#39;./notification.interface&#39;;<br><br>@Component({<br>    selector: &#39;app-notification&#39;,<br>    templateUrl: &#39;./notification.component.html&#39;,<br>    styleUrls: [&#39;./notification.component.css&#39;]<br>})<br>export class NotificationComponent implements OnInit, OnDestroy {<br>    notification: Notification | null = null;<br>    private subscription: Subscription;<br><br>    constructor(private notificationService: NotificationService) {}<br><br>    ngOnInit() {<br>        this.subscription = this.notificationService.notifications.subscribe(<br>            (notif: Notification | null) =&gt; {<br>                this.notification = notif;<br>            }<br>        );<br>    }<br><br>    ngOnDestroy() {<br>        this.subscription.unsubscribe();<br>    }<br>}</pre><pre>&lt;!-- notification.component.html --&gt;<br>&lt;div *ngIf=&quot;notification&quot; class=&quot;notification&quot;&gt;<br>    {{ notification.message }}<br>&lt;/div&gt;</pre><pre>/* notification.component.css */<br>/* Add your styles for notifications here */<br>.notification {<br>    /* Styles for notification */<br>}</pre><h3>Examples of Factory Method Usage in Angular:</h3><p><strong>1. Provider Factories: </strong>In Angular, provider factories are one of the clearest examples of the Factory Method pattern. Factories allow for the lazy creation of services or other dependencies only when they are truly needed. This can be used for configuring and adapting services at the moment of their injection. For instance, you could use a factory provider to create a service with specific settings:</p><pre>{ <br>  provide: SomeService, <br>  useFactory: () =&gt; {<br>    return new SomeService(configureSomehow());<br>  } <br>}</pre><p><strong>2. HttpClientModule and HTTP_INTERCEPTORS:</strong> In Angular, HttpClientModule uses the Factory Method to create HttpClient with a set. of pre-configured interceptors. When you provide interceptors through HTTP_INTERCEPTORS, Angular uses factory methods to instantiate them and integrate them into the HTTP request chain.</p><pre>{ <br>  provide: HTTP_INTERCEPTORS, <br>  useClass: MyCustomInterceptor, <br>  multi: true <br>}</pre><h3>When should you use the Factory Method pattern in Angular?</h3><ul><li>You need to <strong>create a family of related objects or products</strong> that are meant to be used together.</li><li>You want to <strong>provide a library of products without exposing the logic</strong> of their creation.</li><li>Your <strong>code should work with various product variants or configurations without depending on specific classes</strong>.</li></ul><p>If you found this topic interesting and want to deepen your knowledge in the area of design patterns, be sure to check out my other articles on this subject.<br><strong>Creational Design Patterns:</strong></p><ul><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-singleton-98f491c9dad0">Angular’s GoF patterns. Singleton.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-prototype-01082fe5609e">Angular’s GoF patterns. Prototype.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c740fbd3b2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular’s GoF patterns. Singleton.]]></title>
            <link>https://medium.com/@baranoffei/angulars-gof-patterns-singleton-98f491c9dad0?source=rss-a7de86d5a087------2</link>
            <guid isPermaLink="false">https://medium.com/p/98f491c9dad0</guid>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[singleton]]></category>
            <dc:creator><![CDATA[Yevhen Baranov]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 15:26:45 GMT</pubDate>
            <atom:updated>2024-03-04T12:46:59.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCQ6ol98NlGe-SgjvWgJ7A.jpeg" /></figure><h3>Explaining the Singleton Pattern and Its Primary Goal</h3><p>The Singleton pattern is used to ensure that a class has only one instance throughout the application, providing a global access point to this instance. The primary goal of Singleton is to control access to a specific resource or service, ensuring that it is created only once and available from anywhere in the application.</p><h3>Application in Angular</h3><p>In Angular, <strong>Singleton</strong> is often used implicitly through the <strong>Dependency Injection mechanism</strong>.</p><p><strong>Services in Angular are Singletons by default</strong> when they are provided in the root application module (AppModule) or any other module that is imported only once (for example, in a CoreModule that is imported into AppModule).</p><p><strong>Angular DI ensures that each service will have only one instance at the application or module level</strong>, depending on where the service is provided. This makes Singleton an ideal pattern for developing services that need to maintain global state or be available throughout the application, such as services for working with APIs, state management, or authentication.</p><h3>Key Features:</h3><ul><li><strong>Single Instance:</strong> Ensures that a class has only one instance.</li><li><strong>Global Access Point: </strong>Provides a globally accessible access point to this instance.</li><li><strong>Lazy Initialization: </strong>The class instance is created only at the first request, which can contribute to more efficient resource use.</li><li><strong>Controlled Access to a Single Instance: </strong>Singleton ensures centralized control over resources, simplifying state management in the application.</li><li><strong>Resource Savings: </strong>Since only one class instance is created, it contributes to saving memory and other system resources.</li><li><strong>Flexibility: </strong>In some Singleton implementations, the pattern can be extended, allowing subclasses to create their own instances.</li></ul><h3>Advantages:</h3><ul><li><strong>Controlled Access to a Single Instance:</strong> Singleton ensures centralized control over resources, simplifying state management in the application.</li><li><strong>Resource Savings: </strong>Since only one class instance is created, it contributes to saving memory and other system resources.</li><li><strong>Flexibility: </strong>In some Singleton implementations, the pattern can be extended, allowing subclasses to create their own instances.</li></ul><h3>Disadvantages</h3><ul><li><strong>Complicated Testing: </strong>Singleton can complicate the process of unit testing because replacing singleton objects with mocks or stubs in tests can be difficult.</li><li><strong>Hidden Dependency:</strong> Injecting a singleton service can create hidden dependencies between components, making the code harder to understand and debug.</li><li><strong>Scalability Issues: </strong>In multithreaded environments or when developing distributed systems, the use of Singleton can lead to synchronization and scalability issues.</li><li><strong>Violation of the Single Responsibility Principle (SOLID):</strong> Singleton often takes on additional responsibility for managing its lifecycle, which can violate the Single Responsibility Principle.</li></ul><h3>Code example</h3><p>Let’s consider an example of using the Singleton pattern in Angular by creating a service to manage the global data loading state. This service will track whether data loading is currently happening in the application and will allow components to subscribe to loading state changes to display loading indicators or loading messages.</p><h4>Step 1: Creating a Service to Manage Loading State</h4><p>First, let’s create a <strong>LoadingService</strong>, which will be used to notify the application about the start and end of the data loading process.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class LoadingService {<br>  private loadingSubject = new BehaviorSubject&lt;boolean&gt;(false);<br>  public readonly loading$ = this.loadingSubject.asObservable();<br><br>  startLoading() {<br>   this.loadingSubject.next(true);<br>  }<br><br>  stopLoading() {<br>   this.loadingSubject.next(false);<br>  }<br>}</pre><h4>Step 2: Using the Service in Components to Control Loading Indicators</h4><p>Now, the <strong>LoadingService</strong> can be used in components to display a loading indicator when data is being loaded.</p><pre>@Component({<br>  selector: &#39;app-loading-indicator&#39;,<br>  template: `&lt;div *ngIf=&quot;loading&quot;&gt;Loading...&lt;/div&gt;`<br>})<br>export class LoadingIndicatorComponent implements OnDestroy {<br>  loading: boolean = false;<br>  private loadingSubscription: Subscription;<br><br>  constructor(private loadingService: LoadingService) {<br>   this.loadingSubscription = this.loadingService.loading$.subscribe(<br>     isLoading =&gt; { this.loading = isLoading;});<br>  }<br><br>  ngOnDestroy() {<br>   this.loadingSubscription.unsubscribe();<br>  }<br>}</pre><h4>Step 3: Applying the Service in Data Loading Services</h4><p>The <strong>LoadingService</strong> can be integrated with other services that perform data loading to automatically manage loading indicators throughout the application.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class DataService {<br>  constructor(private http: HttpClient, private loadingService: LoadingService) {}<br><br>  fetchData() {<br>   this.loadingService.startLoading();<br>   return this.http.get(&#39;https://api.example.com/data&#39;).pipe(<br>     finalize(() =&gt; this.loadingService.stopLoading())<br>   );<br>  }<br>}</pre><h3>Examples of Singleton Usage in Angular:</h3><h4><strong>1. Services Provided in the Root Module:</strong></h4><p>The Angular framework uses Singleton for services that are provided in the application’s root module or with <strong>`providedIn: ‘root’</strong>`. This means that such services are created only once and are available throughout the application.</p><h4><strong>2. HttpClientModule:</strong></h4><p>The <strong>HttpClientModule</strong> in Angular automatically provides <strong>HttpClient</strong> as a Singleton, offering a centralized way to make HTTP requests without the need to create multiple instances of <strong>HttpClient</strong>.</p><h4><strong>3. Router:</strong></h4><p>The Angular Routing System (<strong>RouterModule</strong>) also utilizes the Singleton pattern to manage navigation state and routes within the application. The Router service is provided as a Singleton, allowing the state of routes and their accessibility to be maintained throughout the entire lifecycle of the application.</p><h3>When should you use the Singleton pattern in Angular?</h3><ul><li>A single instance of a service or object is required throughout the entire lifecycle of the application.</li><li>Global access to a specific resource or service is needed.</li></ul><p>If you found this topic interesting and want to deepen your knowledge in the area of design patterns, be sure to check out my other articles on this subject.<br><strong>Creational Design Patterns:</strong></p><ul><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-factory-method-0c740fbd3b2e">Angular’s GoF patterns. Factory Method.</a></li><li><a href="https://medium.com/@baranoffei/angulars-gof-patterns-prototype-01082fe5609e">Angular’s GoF patterns. Prototype.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98f491c9dad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>