{"url": "https://refactoring.guru/", "titulek": "Refactoring and Design Patterns", "h1": "Hello, world!", "popis": "Refactoring is a controllable process of improving code without creating new functionality. Design Patterns are typical solutions to the commonly occurring problems in software design.", "klicova_slova": "", "kanonicka": "https://refactoring.guru", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru#webpage", "url": "https://refactoring.guru", "inLanguage": "en", "name": "Refactoring and Design Patterns", "description": "Refactoring is a controllable process of improving code without creating new functionality. Design Patterns are typical solutions to the commonly occurring problems in software design.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "primaryImageOfPage": {"@id": "https://refactoring.guru#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru#primaryimage", "url": "https://refactoring.guru/images/refactoring/content/refactoring-preview-3x.png", "width": 1398, "height": 600}}]}], "drobecky": [], "osnova": [{"uroven": 1, "text": "Hello, world!"}, {"uroven": 2, "text": "Refactoring"}, {"uroven": 2, "text": "Design Patterns"}], "markdown": "# Hello, world!\n\n**Refactoring.Guru** makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.\n\nThis site shows you the big picture, how all these subjects intersect, work together, and are still relevant. I don’t pretend to be the inventor of these concepts—most of them were invented by others during the past 20 years. But I think that the connection between refactoring, patterns and general programming principles still remains a mystery for the majority of programmers. This is the problem I would like to solve here.\n\n**P.S.** While I update the project constantly, you can already find tons of info on refactoring and design patterns right here on the website. Track the project progress via [email](/sendy/form) or on [Facebook](https://www.facebook.com/refactoring.guru/).\n\n**— Alexander Shvets**\nThe one-man band behind Refactoring.Guru\n\n## Refactoring\n\nRefactoring is a systematic process of improving code without creating new functionality. Refactoring transforms a mess into clean code and simple design.\n\n[More about Refactoring »](/refactoring)\n\n## Design Patterns\n\nDesign Patterns are typical solutions to commonly occurring problems in software design. They are blueprints that can be taken and customized to solve a particular design problem in your code.\n\n[More about Design Patterns »](/design-patterns)", "znaku_textu": 1396, "slov": 204, "odkazu": 181, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:26:57", "sha256": "f8f569ef8db02a65956d0d000836a2f5e6087330a43254e00242a137cbafe4af", "hloubka": 0, "zdroj_objevu": "seed", "ze_seznamu": true, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://www.facebook.com/refactoring.guru/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns", "titulek": "Design Patterns", "h1": "Design Patterns", "popis": "Design Patterns are typical solutions to commonly occurring problems in software design. They are blueprints that you can customize to solve a particular design problem in your code.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns#webpage", "url": "https://refactoring.guru/design-patterns", "inLanguage": "en", "name": "Design Patterns", "description": "Design Patterns are typical solutions to commonly occurring problems in software design. They are blueprints that you can customize to solve a particular design problem in your code.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns#primaryimage", "url": "https://refactoring.guru/images/patterns/content/index-design-patterns-3x.png", "width": 1398, "height": 600}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}]}]}], "drobecky": ["Home", "Design Patterns"], "osnova": [{"uroven": 1, "text": "Design Patterns"}, {"uroven": 3, "text": "Catalog of patterns"}, {"uroven": 3, "text": "Benefits of patterns"}, {"uroven": 3, "text": "Classification"}, {"uroven": 3, "text": "History of patterns"}, {"uroven": 3, "text": "Criticism of patterns"}, {"uroven": 3, "text": "Dive Into Design Patterns"}], "markdown": "# Design Patterns\n\n**Design patterns** are typical solutions to common problems\nin software design. Each pattern is like a blueprint\nthat you can customize to solve a particular\ndesign problem in your code.\n\n[What's a design pattern?](/design-patterns/what-is-pattern)\n\n### Catalog of patterns\n\nList of 22 classic design patterns,\ngrouped by their intent.\n\n[Look inside the catalog »](/design-patterns/catalog)\n\n### Benefits of patterns\n\nPatterns are a toolkit of solutions to common\nproblems in software design. They define\na common language that helps your team\ncommunicate more efficiently.\n\n[More about the benefits »](/design-patterns/why-learn-patterns)\n\n### Classification\n\nDesign patterns differ by their complexity, level of\ndetail and scale of applicability. In addition,\nthey can be categorized by their intent\nand divided into three groups.\n\n[More about the categories »](/design-patterns/classification)\n\n### History of patterns\n\nWho invented patterns and when?\nCan you use patterns outside software\ndevelopment? How do you do that?\n\n[More about the history »](/design-patterns/history)\n\n### Criticism of patterns\n\nAre patterns as good as advertised?\nIs it always possible to use them?\nCan patterns sometimes be harmful?\n\n[More about the criticism »](/design-patterns/criticism)\n\n### Dive Into Design Patterns\n\nCheck out our ebook on design\npatterns and principles. It's available in\nPDF/ePUB/MOBI formats and includes the\narchive with code examples in\nJava, C#, C++, PHP, Python, Ruby,\nGo, Swift, & TypeScript.\n\n[Learn more about the book](/design-patterns/book)", "znaku_textu": 1533, "slov": 223, "odkazu": 180, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:26:58", "sha256": "b3c1133bc8d054a03a85adcac43d27ef4c8b08215a12e6cc98440f40febdcedd", "hloubka": 0, "zdroj_objevu": "seed", "ze_seznamu": true, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns/abstract-factory", "titulek": "Abstract Factory", "h1": "Abstract Factory", "popis": "Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/abstract-factory", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/abstract-factory#webpage", "url": "https://refactoring.guru/design-patterns/abstract-factory", "inLanguage": "en", "name": "Abstract Factory", "description": "Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/abstract-factory#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/abstract-factory#primaryimage", "url": "https://refactoring.guru/images/patterns/content/abstract-factory/abstract-factory-en-3x.png", "width": 1920, "height": 1200}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/abstract-factory#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Design Patterns", "image": {"@id": "https://refactoring.guru/design-patterns/abstract-factory#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/abstract-factory#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Creational Patterns", "item": "https://refactoring.guru/design-patterns/creational-patterns"}]}]}], "drobecky": ["Home", "Design Patterns", "Creational Patterns"], "osnova": [{"uroven": 1, "text": "Abstract Factory"}, {"uroven": 2, "text": "Intent"}, {"uroven": 2, "text": "Problem"}, {"uroven": 2, "text": "Solution"}, {"uroven": 2, "text": "Structure"}, {"uroven": 2, "text": "Pseudocode"}, {"uroven": 2, "text": "Applicability"}, {"uroven": 2, "text": "How to Implement"}, {"uroven": 2, "text": "Pros and Cons"}, {"uroven": 2, "text": "Relations with Other Patterns"}, {"uroven": 2, "text": "Code Examples"}, {"uroven": 2, "text": "Extra Content"}], "markdown": "# Abstract Factory\n\n## Intent\n\n**Abstract Factory** is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.\n\n## Problem\n\nImagine that you’re creating a furniture shop simulator. Your code consists of classes that represent:\n\n1. A family of related products, say: `Chair` + `Sofa` + `CoffeeTable`.\n2. Several variants of this family. For example, products `Chair` + `Sofa` + `CoffeeTable` are available in these variants: `Modern`, `Victorian`, `ArtDeco`.\n\nProduct families and their variants.\n\nYou need a way to create individual furniture objects so that they match other objects of the same family. Customers get quite mad when they receive non-matching furniture.\n\nA Modern-style sofa doesn’t match Victorian-style chairs.\n\nAlso, you don’t want to change existing code when adding new products or families of products to the program. Furniture vendors update their catalogs very often, and you wouldn’t want to change the core code each time it happens.\n\n## Solution\n\nThe first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all variants of products follow those interfaces. For example, all chair variants can implement the `Chair` interface; all coffee table variants can implement the `CoffeeTable` interface, and so on.\n\nAll variants of the same object must be moved to a single class hierarchy.\n\nThe next move is to declare the *Abstract Factory*—an interface with a list of creation methods for all products that are part of the product family (for example, `createChair`, `createSofa` and `createCoffeeTable`). These methods must return **abstract** product types represented by the interfaces we extracted previously: `Chair`, `Sofa`, `CoffeeTable` and so on.\n\nEach concrete factory corresponds to a specific product variant.\n\nNow, how about the product variants? For each variant of a product family, we create a separate factory class based on the `AbstractFactory` interface. A factory is a class that returns products of a particular kind. For example, the `ModernFurnitureFactory` can only create `ModernChair`, `ModernSofa` and `ModernCoffeeTable` objects.\n\nThe client code has to work with both factories and products via their respective abstract interfaces. This lets you change the type of a factory that you pass to the client code, as well as the product variant that the client code receives, without breaking the actual client code.\n\nThe client shouldn’t care about the concrete class of the factory it works with.\n\nSay the client wants a factory to produce a chair. The client doesn’t have to be aware of the factory’s class, nor does it matter what kind of chair it gets. Whether it’s a Modern model or a Victorian-style chair, the client must treat all chairs in the same manner, using the abstract `Chair` interface. With this approach, the only thing that the client knows about the chair is that it implements the `sitOn` method in some way. Also, whichever variant of the chair is returned, it’ll always match the type of sofa or coffee table produced by the same factory object.\n\nThere’s one more thing left to clarify: if the client is only exposed to the abstract interfaces, what creates the actual factory objects? Usually, the application creates a concrete factory object at the initialization stage. Just before that, the app must select the factory type depending on the configuration or the environment settings.\n\n## Structure\n\n1. **Abstract Products** declare interfaces for a set of distinct but related products which make up a product family.\n2. **Concrete Products** are various implementations of abstract products, grouped by variants. Each abstract product (chair/sofa) must be implemented in all given variants (Victorian/Modern).\n3. The **Abstract Factory** interface declares a set of methods for creating each of the abstract products.\n4. **Concrete Factories** implement creation methods of the abstract factory. Each concrete factory corresponds to a specific variant of products and creates only those product variants.\n5. Although concrete factories instantiate concrete products, signatures of their creation methods must return corresponding *abstract* products. This way the client code that uses a factory doesn’t get coupled to the specific variant of the product it gets from a factory. The **Client** can work with any concrete factory/product variant, as long as it communicates with their objects via abstract interfaces.\n\n## Pseudocode\n\nThis example illustrates how the **Abstract Factory** pattern can be used for creating cross-platform UI elements without coupling the client code to concrete UI classes, while keeping all created elements consistent with a selected operating system.\n\nThe cross-platform UI classes example.\n\nThe same UI elements in a cross-platform application are expected to behave similarly, but look a little bit different under different operating systems. Moreover, it’s your job to make sure that the UI elements match the style of the current operating system. You wouldn’t want your program to render macOS controls when it’s executed in Windows.\n\nThe Abstract Factory interface declares a set of creation methods that the client code can use to produce different types of UI elements. Concrete factories correspond to specific operating systems and create the UI elements that match that particular OS.\n\nIt works like this: when an application launches, it checks the type of the current operating system. The app uses this information to create a factory object from a class that matches the operating system. The rest of the code uses this factory to create UI elements. This prevents the wrong elements from being created.\n\nWith this approach, the client code doesn’t depend on concrete classes of factories and UI elements as long as it works with these objects via their abstract interfaces. This also lets the client code support other factories or UI elements that you might add in the future.\n\nAs a result, you don’t need to modify the client code each time you add a new variation of UI elements to your app. You just have to create a new factory class that produces these elements and slightly modify the app’s initialization code so it selects that class when appropriate.\n\n```\n// The abstract factory interface declares a set of methods that\n// return different abstract products. These products are called\n// a family and are related by a high-level theme or concept.\n// Products of one family are usually able to collaborate among\n// themselves. A family of products may have several variants,\n// but the products of one variant are incompatible with the\n// products of another variant.\ninterface GUIFactory is\n method createButton():Button\n method createCheckbox():Checkbox\n\n// Concrete factories produce a family of products that belong\n// to a single variant. The factory guarantees that the\n// resulting products are compatible. Signatures of the concrete\n// factory's methods return an abstract product, while inside\n// the method a concrete product is instantiated.\nclass WinFactory implements GUIFactory is\n method createButton():Button is\n return new WinButton()\n method createCheckbox():Checkbox is\n return new WinCheckbox()\n\n// Each concrete factory has a corresponding product variant.\nclass MacFactory implements GUIFactory is\n method createButton():Button is\n return new MacButton()\n method createCheckbox():Checkbox is\n return new MacCheckbox()\n\n// Each distinct product of a product family should have a base\n// interface. All variants of the product must implement this\n// interface.\ninterface Button is\n method paint()\n\n// Concrete products are created by corresponding concrete\n// factories.\nclass WinButton implements Button is\n method paint() is\n // Render a button in Windows style.\n\nclass MacButton implements Button is\n method paint() is\n // Render a button in macOS style.\n\n// Here's the base interface of another product. All products\n// can interact with each other, but proper interaction is\n// possible only between products of the same concrete variant.\ninterface Checkbox is\n method paint()\n\nclass WinCheckbox implements Checkbox is\n method paint() is\n // Render a checkbox in Windows style.\n\nclass MacCheckbox implements Checkbox is\n method paint() is\n // Render a checkbox in macOS style.\n\n// The client code works with factories and products only\n// through abstract types: GUIFactory, Button and Checkbox. This\n// lets you pass any factory or product subclass to the client\n// code without breaking it.\nclass Application is\n private field factory: GUIFactory\n private field button: Button\n constructor Application(factory: GUIFactory) is\n this.factory = factory\n method createUI() is\n this.button = factory.createButton()\n method paint() is\n button.paint()\n\n// The application picks the factory type depending on the\n// current configuration or environment settings and creates it\n// at runtime (usually at the initialization stage).\nclass ApplicationConfigurator is\n method main() is\n config = readApplicationConfigFile()\n\n if (config.OS == \"Windows\") then\n factory = new WinFactory()\n else if (config.OS == \"Mac\") then\n factory = new MacFactory()\n else\n throw new Exception(\"Error! Unknown operating system.\")\n\n Application app = new Application(factory)\n```\n\n## Applicability\n\nUse the Abstract Factory when your code needs to work with various families of related products, but you don’t want it to depend on the concrete classes of those products—they might be unknown beforehand or you simply want to allow for future extensibility.\n\nThe Abstract Factory provides you with an interface for creating objects from each class of the product family. As long as your code creates objects via this interface, you don’t have to worry about creating the wrong variant of a product which doesn’t match the products already created by your app.\n\nConsider implementing the Abstract Factory when you have a class with a set of [Factory Methods](/design-patterns/factory-method) that blur its primary responsibility.\n\nIn a well-designed program *each class is responsible only for one thing*. When a class deals with multiple product types, it may be worth extracting its factory methods into a stand-alone factory class or a full-blown Abstract Factory implementation.\n\n## How to Implement\n\n1. Map out a matrix of distinct product types versus variants of these products.\n2. Declare abstract product interfaces for all product types. Then make all concrete product classes implement these interfaces.\n3. Declare the abstract factory interface with a set of creation methods for all abstract products.\n4. Implement a set of concrete factory classes, one for each product variant.\n5. Create factory initialization code somewhere in the app. It should instantiate one of the concrete factory classes, depending on the application configuration or the current environment. Pass this factory object to all classes that construct products.\n6. Scan through the code and find all direct calls to product constructors. Replace them with calls to the appropriate creation method on the factory object.\n\n## Pros and Cons\n\n- You can be sure that the products you’re getting from a factory are compatible with each other.\n- You avoid tight coupling between concrete products and client code.\n- *Single Responsibility Principle* . You can extract the product creation code into one place, making the code easier to support.\n- *Open/Closed Principle* . You can introduce new variants of products without breaking existing client code.\n\n- The code may become more complicated than it should be, since a lot of new interfaces and classes are introduced along with the pattern.\n\n## Relations with Other Patterns\n\n- Many designs start by using [Factory Method](/design-patterns/factory-method) (less complicated and more customizable via subclasses) and evolve toward [Abstract Factory](/design-patterns/abstract-factory), [Prototype](/design-patterns/prototype), or [Builder](/design-patterns/builder) (more flexible, but more complicated).\n- [Builder](/design-patterns/builder) focuses on constructing complex objects step by step. [Abstract Factory](/design-patterns/abstract-factory) specializes in creating families of related objects. *Abstract Factory* returns the product immediately, whereas *Builder* lets you run some additional construction steps before fetching the product.\n- [Abstract Factory](/design-patterns/abstract-factory) classes are often based on a set of [Factory Methods](/design-patterns/factory-method), but you can also use [Prototype](/design-patterns/prototype) to compose the methods on these classes.\n- [Abstract Factory](/design-patterns/abstract-factory) can serve as an alternative to [Facade](/design-patterns/facade) when you only want to hide the way the subsystem objects are created from the client code.\n- You can use [Abstract Factory](/design-patterns/abstract-factory) along with [Bridge](/design-patterns/bridge). This pairing is useful when some abstractions defined by *Bridge* can only work with specific implementations. In this case, *Abstract Factory* can encapsulate these relations and hide the complexity from the client code.\n- [Abstract Factories](/design-patterns/abstract-factory), [Builders](/design-patterns/builder) and [Prototypes](/design-patterns/prototype) can all be implemented as [Singletons](/design-patterns/singleton).\n\n## Code Examples\n\n## Extra Content\n\n- Read our [Factory Comparison](/design-patterns/factory-comparison) to learn more about the differences between various factory patterns and concepts.", "znaku_textu": 13521, "slov": 2036, "odkazu": 191, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:26:59", "sha256": "949588265992d3b5cd15bf4f6cfd57640e6d3b5257849d10ff7eeef11fa4bfae", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/abstract-factory", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example", "titulek": "Abstract Factory in C++ / Design Patterns", "h1": "Abstract Factory in C++", "popis": "Abstract Factory pattern in C++. Full code example in C++ with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#webpage", "url": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example", "inLanguage": "en", "name": "Abstract Factory in C++", "description": "Abstract Factory pattern in C++. Full code example in C++ with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/abstract-factory-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in C++", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Abstract Factory", "image": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Abstract Factory", "item": "https://refactoring.guru/design-patterns/abstract-factory"}, {"@type": "ListItem", "position": 4, "name": "C++", "item": "https://refactoring.guru/design-patterns/cpp"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/cpp/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in C++", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "C++", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Abstract Factory", "C++"], "osnova": [{"uroven": 1, "text": "Abstract Factory in C++"}, {"uroven": 2, "text": "Conceptual Example"}, {"uroven": 4, "text": "main.cc: Conceptual example"}, {"uroven": 4, "text": "Output.txt: Execution result"}, {"uroven": 2, "text": "Abstract Factory in Other Languages"}], "markdown": "# **Abstract Factory** in C++\n\n**Abstract Factory** is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.\n\nAbstract Factory defines an interface for creating all distinct products but leaves the actual product creation to concrete factory classes. Each factory type corresponds to a certain product variety.\n\nThe client code calls the creation methods of a factory object instead of creating products directly with a constructor call (`new` operator). Since a factory corresponds to a single product variant, all its products will be compatible.\n\nClient code works with factories and products only through their abstract interfaces. This lets the client code work with any product variants, created by the factory object. You just create a new concrete factory class and pass it to the client code.\n\n> If you can’t figure out the difference between various factory patterns and concepts, then read our [Factory Comparison](/design-patterns/factory-comparison).\n\n[Learn more about Abstract Factory](/design-patterns/abstract-factory)\n\n**Complexity:**\n\n**Popularity:**\n\n**Usage examples:** The Abstract Factory pattern is pretty common in C++ code. Many frameworks and libraries use it to provide a way to extend and customize their standard components.\n\n**Identification:** The pattern is easy to recognize by methods, which return a factory object. Then, the factory is used for creating specific sub-components.\n\n## Conceptual Example\n\nThis example illustrates the structure of the **Abstract Factory** design pattern. It focuses on answering these questions:\n\n- What classes does it consist of?\n- What roles do these classes play?\n- In what way the elements of the pattern are related?\n\n#### **main.cc:** Conceptual example\n\n```\n/**\n * Each distinct product of a product family should have a base interface. All\n * variants of the product must implement this interface.\n */\nclass AbstractProductA {\n public:\n virtual ~AbstractProductA(){};\n virtual std::string UsefulFunctionA() const = 0;\n};\n\n/**\n * Concrete Products are created by corresponding Concrete Factories.\n */\nclass ConcreteProductA1 : public AbstractProductA {\n public:\n std::string UsefulFunctionA() const override {\n return \"The result of the product A1.\";\n }\n};\n\nclass ConcreteProductA2 : public AbstractProductA {\n std::string UsefulFunctionA() const override {\n return \"The result of the product A2.\";\n }\n};\n\n/**\n * Here's the the base interface of another product. All products can interact\n * with each other, but proper interaction is possible only between products of\n * the same concrete variant.\n */\nclass AbstractProductB {\n /**\n * Product B is able to do its own thing...\n */\n public:\n virtual ~AbstractProductB(){};\n virtual std::string UsefulFunctionB() const = 0;\n /**\n * ...but it also can collaborate with the ProductA.\n *\n * The Abstract Factory makes sure that all products it creates are of the\n * same variant and thus, compatible.\n */\n virtual std::string AnotherUsefulFunctionB(const AbstractProductA &collaborator) const = 0;\n};\n\n/**\n * Concrete Products are created by corresponding Concrete Factories.\n */\nclass ConcreteProductB1 : public AbstractProductB {\n public:\n std::string UsefulFunctionB() const override {\n return \"The result of the product B1.\";\n }\n /**\n * The variant, Product B1, is only able to work correctly with the variant,\n * Product A1. Nevertheless, it accepts any instance of AbstractProductA as an\n * argument.\n */\n std::string AnotherUsefulFunctionB(const AbstractProductA &collaborator) const override {\n const std::string result = collaborator.UsefulFunctionA();\n return \"The result of the B1 collaborating with ( \" + result + \" )\";\n }\n};\n\nclass ConcreteProductB2 : public AbstractProductB {\n public:\n std::string UsefulFunctionB() const override {\n return \"The result of the product B2.\";\n }\n /**\n * The variant, Product B2, is only able to work correctly with the variant,\n * Product A2. Nevertheless, it accepts any instance of AbstractProductA as an\n * argument.\n */\n std::string AnotherUsefulFunctionB(const AbstractProductA &collaborator) const override {\n const std::string result = collaborator.UsefulFunctionA();\n return \"The result of the B2 collaborating with ( \" + result + \" )\";\n }\n};\n\n/**\n * The Abstract Factory interface declares a set of methods that return\n * different abstract products. These products are called a family and are\n * related by a high-level theme or concept. Products of one family are usually\n * able to collaborate among themselves. A family of products may have several\n * variants, but the products of one variant are incompatible with products of\n * another.\n */\nclass AbstractFactory {\n public:\n virtual ~AbstractFactory(){};\n virtual AbstractProductA *CreateProductA() const = 0;\n virtual AbstractProductB *CreateProductB() const = 0;\n};\n\n/**\n * Concrete Factories produce a family of products that belong to a single\n * variant. The factory guarantees that resulting products are compatible. Note\n * that signatures of the Concrete Factory's methods return an abstract product,\n * while inside the method a concrete product is instantiated.\n */\nclass ConcreteFactory1 : public AbstractFactory {\n public:\n AbstractProductA *CreateProductA() const override {\n return new ConcreteProductA1();\n }\n AbstractProductB *CreateProductB() const override {\n return new ConcreteProductB1();\n }\n};\n\n/**\n * Each Concrete Factory has a corresponding product variant.\n */\nclass ConcreteFactory2 : public AbstractFactory {\n public:\n AbstractProductA *CreateProductA() const override {\n return new ConcreteProductA2();\n }\n AbstractProductB *CreateProductB() const override {\n return new ConcreteProductB2();\n }\n};\n\n/**\n * The client code works with factories and products only through abstract\n * types: AbstractFactory and AbstractProduct. This lets you pass any factory or\n * product subclass to the client code without breaking it.\n */\n\nvoid ClientCode(const AbstractFactory &factory) {\n const AbstractProductA *product_a = factory.CreateProductA();\n const AbstractProductB *product_b = factory.CreateProductB();\n std::cout << product_b->UsefulFunctionB() << \"\\n\";\n std::cout << product_b->AnotherUsefulFunctionB(*product_a) << \"\\n\";\n delete product_a;\n delete product_b;\n}\n\nint main() {\n std::cout << \"Client: Testing client code with the first factory type:\\n\";\n ConcreteFactory1 *f1 = new ConcreteFactory1();\n ClientCode(*f1);\n delete f1;\n std::cout << std::endl;\n std::cout << \"Client: Testing the same client code with the second factory type:\\n\";\n ConcreteFactory2 *f2 = new ConcreteFactory2();\n ClientCode(*f2);\n delete f2;\n return 0;\n}\n```\n\n#### **Output.txt:** Execution result\n\n```\nClient: Testing client code with the first factory type:\nThe result of the product B1.\nThe result of the B1 collaborating with the (The result of the product A1.)\n\nClient: Testing the same client code with the second factory type:\nThe result of the product B2.\nThe result of the B2 collaborating with the (The result of the product A2.)\n```\n\n## **Abstract Factory** in Other Languages", "znaku_textu": 6915, "slov": 972, "odkazu": 195, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:00", "sha256": "3ccbbe595f29ff70a661b68ff16e3d092ce37837c48763524e9e2a3968570fad", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/abstract-factory/cpp/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example", "titulek": "Abstract Factory in C# / Design Patterns", "h1": "Abstract Factory in C#", "popis": "Abstract Factory pattern in C#. Full code example in C# with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#webpage", "url": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example", "inLanguage": "en", "name": "Abstract Factory in C#", "description": "Abstract Factory pattern in C#. Full code example in C# with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/abstract-factory-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in C#", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Abstract Factory", "image": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Abstract Factory", "item": "https://refactoring.guru/design-patterns/abstract-factory"}, {"@type": "ListItem", "position": 4, "name": "C#", "item": "https://refactoring.guru/design-patterns/csharp"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/csharp/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in C#", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "C#", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Abstract Factory", "C#"], "osnova": [{"uroven": 1, "text": "Abstract Factory in C#"}, {"uroven": 2, "text": "Conceptual Example"}, {"uroven": 4, "text": "Program.cs: Conceptual example"}, {"uroven": 4, "text": "Output.txt: Execution result"}, {"uroven": 2, "text": "Abstract Factory in Other Languages"}], "markdown": "# **Abstract Factory** in C#\n\n**Abstract Factory** is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.\n\nAbstract Factory defines an interface for creating all distinct products but leaves the actual product creation to concrete factory classes. Each factory type corresponds to a certain product variety.\n\nThe client code calls the creation methods of a factory object instead of creating products directly with a constructor call (`new` operator). Since a factory corresponds to a single product variant, all its products will be compatible.\n\nClient code works with factories and products only through their abstract interfaces. This lets the client code work with any product variants, created by the factory object. You just create a new concrete factory class and pass it to the client code.\n\n> If you can’t figure out the difference between various factory patterns and concepts, then read our [Factory Comparison](/design-patterns/factory-comparison).\n\n[Learn more about Abstract Factory](/design-patterns/abstract-factory)\n\n**Complexity:**\n\n**Popularity:**\n\n**Usage examples:** The Abstract Factory pattern is pretty common in C# code. Many frameworks and libraries use it to provide a way to extend and customize their standard components.\n\n**Identification:** The pattern is easy to recognize by methods, which return a factory object. Then, the factory is used for creating specific sub-components.\n\n## Conceptual Example\n\nThis example illustrates the structure of the **Abstract Factory** design pattern. It focuses on answering these questions:\n\n- What classes does it consist of?\n- What roles do these classes play?\n- In what way the elements of the pattern are related?\n\n#### **Program.cs:** Conceptual example\n\n```\nusing System;\n\nnamespace RefactoringGuru.DesignPatterns.AbstractFactory.Conceptual\n{\n // The Abstract Factory interface declares a set of methods that return\n // different abstract products. These products are called a family and are\n // related by a high-level theme or concept. Products of one family are\n // usually able to collaborate among themselves. A family of products may\n // have several variants, but the products of one variant are incompatible\n // with products of another.\n public interface IAbstractFactory\n {\n IAbstractProductA CreateProductA();\n\n IAbstractProductB CreateProductB();\n }\n\n // Concrete Factories produce a family of products that belong to a single\n // variant. The factory guarantees that resulting products are compatible.\n // Note that signatures of the Concrete Factory's methods return an abstract\n // product, while inside the method a concrete product is instantiated.\n class ConcreteFactory1 : IAbstractFactory\n {\n public IAbstractProductA CreateProductA()\n {\n return new ConcreteProductA1();\n }\n\n public IAbstractProductB CreateProductB()\n {\n return new ConcreteProductB1();\n }\n }\n\n // Each Concrete Factory has a corresponding product variant.\n class ConcreteFactory2 : IAbstractFactory\n {\n public IAbstractProductA CreateProductA()\n {\n return new ConcreteProductA2();\n }\n\n public IAbstractProductB CreateProductB()\n {\n return new ConcreteProductB2();\n }\n }\n\n // Each distinct product of a product family should have a base interface.\n // All variants of the product must implement this interface.\n public interface IAbstractProductA\n {\n string UsefulFunctionA();\n }\n\n // Concrete Products are created by corresponding Concrete Factories.\n class ConcreteProductA1 : IAbstractProductA\n {\n public string UsefulFunctionA()\n {\n return \"The result of the product A1.\";\n }\n }\n\n class ConcreteProductA2 : IAbstractProductA\n {\n public string UsefulFunctionA()\n {\n return \"The result of the product A2.\";\n }\n }\n\n // Here's the the base interface of another product. All products can\n // interact with each other, but proper interaction is possible only between\n // products of the same concrete variant.\n public interface IAbstractProductB\n {\n // Product B is able to do its own thing...\n string UsefulFunctionB();\n\n // ...but it also can collaborate with the ProductA.\n //\n // The Abstract Factory makes sure that all products it creates are of\n // the same variant and thus, compatible.\n string AnotherUsefulFunctionB(IAbstractProductA collaborator);\n }\n\n // Concrete Products are created by corresponding Concrete Factories.\n class ConcreteProductB1 : IAbstractProductB\n {\n public string UsefulFunctionB()\n {\n return \"The result of the product B1.\";\n }\n\n // The variant, Product B1, is only able to work correctly with the\n // variant, Product A1. Nevertheless, it accepts any instance of\n // AbstractProductA as an argument.\n public string AnotherUsefulFunctionB(IAbstractProductA collaborator)\n {\n var result = collaborator.UsefulFunctionA();\n\n return $\"The result of the B1 collaborating with the ({result})\";\n }\n }\n\n class ConcreteProductB2 : IAbstractProductB\n {\n public string UsefulFunctionB()\n {\n return \"The result of the product B2.\";\n }\n\n // The variant, Product B2, is only able to work correctly with the\n // variant, Product A2. Nevertheless, it accepts any instance of\n // AbstractProductA as an argument.\n public string AnotherUsefulFunctionB(IAbstractProductA collaborator)\n {\n var result = collaborator.UsefulFunctionA();\n\n return $\"The result of the B2 collaborating with the ({result})\";\n }\n }\n\n // The client code works with factories and products only through abstract\n // types: AbstractFactory and AbstractProduct. This lets you pass any\n // factory or product subclass to the client code without breaking it.\n class Client\n {\n public void Main()\n {\n // The client code can work with any concrete factory class.\n Console.WriteLine(\"Client: Testing client code with the first factory type...\");\n ClientMethod(new ConcreteFactory1());\n Console.WriteLine();\n\n Console.WriteLine(\"Client: Testing the same client code with the second factory type...\");\n ClientMethod(new ConcreteFactory2());\n }\n\n public void ClientMethod(IAbstractFactory factory)\n {\n var productA = factory.CreateProductA();\n var productB = factory.CreateProductB();\n\n Console.WriteLine(productB.UsefulFunctionB());\n Console.WriteLine(productB.AnotherUsefulFunctionB(productA));\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n new Client().Main();\n }\n }\n}\n```\n\n#### **Output.txt:** Execution result\n\n```\nClient: Testing client code with the first factory type...\nThe result of the product B1.\nThe result of the B1 collaborating with the (The result of the product A1.)\n\nClient: Testing the same client code with the second factory type...\nThe result of the product B2.\nThe result of the B2 collaborating with the (The result of the product A2.)\n```\n\n## **Abstract Factory** in Other Languages", "znaku_textu": 6641, "slov": 913, "odkazu": 195, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:01", "sha256": "1c51e33d1d0602ec68395f65d914c8a2097fcc08ad84d5c67125c6cf48e2f8b1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/abstract-factory/csharp/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns/abstract-factory/go/example", "titulek": "Abstract Factory in Go / Design Patterns", "h1": "Abstract Factory in Go", "popis": "Abstract Factory pattern in Go. Full code example in Go with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/abstract-factory/go/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#webpage", "url": "https://refactoring.guru/design-patterns/abstract-factory/go/example", "inLanguage": "en", "name": "Abstract Factory in Go", "description": "Abstract Factory pattern in Go. Full code example in Go with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/abstract-factory-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in Go", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Abstract Factory", "image": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Abstract Factory", "item": "https://refactoring.guru/design-patterns/abstract-factory"}, {"@type": "ListItem", "position": 4, "name": "Go", "item": "https://refactoring.guru/design-patterns/go"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/go/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in Go", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "Go", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Abstract Factory", "Go"], "osnova": [{"uroven": 1, "text": "Abstract Factory in Go"}, {"uroven": 2, "text": "Conceptual Example"}, {"uroven": 4, "text": "iSportsFactory.go: Abstract factory interface"}, {"uroven": 4, "text": "adidas.go: Concrete factory"}, {"uroven": 4, "text": "nike.go: Concrete factory"}, {"uroven": 4, "text": "iShoe.go: Abstract product"}, {"uroven": 4, "text": "adidasShoe.go: Concrete product"}, {"uroven": 4, "text": "nikeShoe.go: Concrete product"}, {"uroven": 4, "text": "iShirt.go: Abstract product"}, {"uroven": 4, "text": "adidasShirt.go: Concrete product"}, {"uroven": 4, "text": "nikeShirt.go: Concrete product"}, {"uroven": 4, "text": "main.go: Client code"}, {"uroven": 4, "text": "output.txt: Execution result"}, {"uroven": 2, "text": "Abstract Factory in Other Languages"}], "markdown": "# **Abstract Factory** in Go\n\n**Abstract Factory** is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.\n\nAbstract Factory defines an interface for creating all distinct products but leaves the actual product creation to concrete factory classes. Each factory type corresponds to a certain product variety.\n\nThe client code calls the creation methods of a factory object instead of creating products directly with a constructor call (`new` operator). Since a factory corresponds to a single product variant, all its products will be compatible.\n\nClient code works with factories and products only through their abstract interfaces. This lets the client code work with any product variants, created by the factory object. You just create a new concrete factory class and pass it to the client code.\n\n> If you can’t figure out the difference between various factory patterns and concepts, then read our [Factory Comparison](/design-patterns/factory-comparison).\n\n[Learn more about Abstract Factory](/design-patterns/abstract-factory)\n\n## Conceptual Example\n\nSay, you need to buy a sports kit, a set of two different products: a pair of shoes and a shirt. You would want to buy a full sports kit of the same brand to match all the items.\n\nIf we try to turn this into code, the abstract factory will help us create sets of products so that they would always match each other.\n\n#### **iSportsFactory.go:** Abstract factory interface\n\n```\npackage main\n\nimport \"fmt\"\n\ntype ISportsFactory interface {\n\tmakeShoe() IShoe\n\tmakeShirt() IShirt\n}\n\nfunc GetSportsFactory(brand string) (ISportsFactory, error) {\n\tif brand == \"adidas\" {\n\t\treturn &Adidas{}, nil\n\t}\n\n\tif brand == \"nike\" {\n\t\treturn &Nike{}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Wrong brand type passed\")\n}\n```\n\n#### **adidas.go:** Concrete factory\n\n```\npackage main\n\ntype Adidas struct {\n}\n\nfunc (a *Adidas) makeShoe() IShoe {\n\treturn &AdidasShoe{\n\t\tShoe: Shoe{\n\t\t\tlogo: \"adidas\",\n\t\t\tsize: 14,\n\t\t},\n\t}\n}\n\nfunc (a *Adidas) makeShirt() IShirt {\n\treturn &AdidasShirt{\n\t\tShirt: Shirt{\n\t\t\tlogo: \"adidas\",\n\t\t\tsize: 14,\n\t\t},\n\t}\n}\n```\n\n#### **nike.go:** Concrete factory\n\n```\npackage main\n\ntype Nike struct {\n}\n\nfunc (n *Nike) makeShoe() IShoe {\n\treturn &NikeShoe{\n\t\tShoe: Shoe{\n\t\t\tlogo: \"nike\",\n\t\t\tsize: 14,\n\t\t},\n\t}\n}\n\nfunc (n *Nike) makeShirt() IShirt {\n\treturn &NikeShirt{\n\t\tShirt: Shirt{\n\t\t\tlogo: \"nike\",\n\t\t\tsize: 14,\n\t\t},\n\t}\n}\n```\n\n#### **iShoe.go:** Abstract product\n\n```\npackage main\n\ntype IShoe interface {\n\tsetLogo(logo string)\n\tsetSize(size int)\n\tgetLogo() string\n\tgetSize() int\n}\n\ntype Shoe struct {\n\tlogo string\n\tsize int\n}\n\nfunc (s *Shoe) setLogo(logo string) {\n\ts.logo = logo\n}\n\nfunc (s *Shoe) getLogo() string {\n\treturn s.logo\n}\n\nfunc (s *Shoe) setSize(size int) {\n\ts.size = size\n}\n\nfunc (s *Shoe) getSize() int {\n\treturn s.size\n}\n```\n\n#### **adidasShoe.go:** Concrete product\n\n```\npackage main\n\ntype AdidasShoe struct {\n\tShoe\n}\n```\n\n#### **nikeShoe.go:** Concrete product\n\n```\npackage main\n\ntype NikeShoe struct {\n\tShoe\n}\n```\n\n#### **iShirt.go:** Abstract product\n\n```\npackage main\n\ntype IShirt interface {\n\tsetLogo(logo string)\n\tsetSize(size int)\n\tgetLogo() string\n\tgetSize() int\n}\n\ntype Shirt struct {\n\tlogo string\n\tsize int\n}\n\nfunc (s *Shirt) setLogo(logo string) {\n\ts.logo = logo\n}\n\nfunc (s *Shirt) getLogo() string {\n\treturn s.logo\n}\n\nfunc (s *Shirt) setSize(size int) {\n\ts.size = size\n}\n\nfunc (s *Shirt) getSize() int {\n\treturn s.size\n}\n```\n\n#### **adidasShirt.go:** Concrete product\n\n```\npackage main\n\ntype AdidasShirt struct {\n\tShirt\n}\n```\n\n#### **nikeShirt.go:** Concrete product\n\n```\npackage main\n\ntype NikeShirt struct {\n\tShirt\n}\n```\n\n#### **main.go:** Client code\n\n```\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tadidasFactory, _ := GetSportsFactory(\"adidas\")\n\tnikeFactory, _ := GetSportsFactory(\"nike\")\n\n\tnikeShoe := nikeFactory.makeShoe()\n\tnikeShirt := nikeFactory.makeShirt()\n\n\tadidasShoe := adidasFactory.makeShoe()\n\tadidasShirt := adidasFactory.makeShirt()\n\n\tprintShoeDetails(nikeShoe)\n\tprintShirtDetails(nikeShirt)\n\n\tprintShoeDetails(adidasShoe)\n\tprintShirtDetails(adidasShirt)\n}\n\nfunc printShoeDetails(s IShoe) {\n\tfmt.Printf(\"Logo: %s\", s.getLogo())\n\tfmt.Println()\n\tfmt.Printf(\"Size: %d\", s.getSize())\n\tfmt.Println()\n}\n\nfunc printShirtDetails(s IShirt) {\n\tfmt.Printf(\"Logo: %s\", s.getLogo())\n\tfmt.Println()\n\tfmt.Printf(\"Size: %d\", s.getSize())\n\tfmt.Println()\n}\n```\n\n#### **output.txt:** Execution result\n\n```\nLogo: nike\nSize: 14\nLogo: nike\nSize: 14\nLogo: adidas\nSize: 14\nLogo: adidas\nSize: 14\n```\n\n## **Abstract Factory** in Other Languages", "znaku_textu": 4335, "slov": 623, "odkazu": 204, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:02", "sha256": "19ed5b34a3c89baf0b90096b0ec289825b9958e8fe11712af1c8142b41773ca6", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/abstract-factory/go/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns/abstract-factory/java/example", "titulek": "Abstract Factory in Java / Design Patterns", "h1": "Abstract Factory in Java", "popis": "Abstract Factory pattern in Java. Full code example in Java with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/abstract-factory/java/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#webpage", "url": "https://refactoring.guru/design-patterns/abstract-factory/java/example", "inLanguage": "en", "name": "Abstract Factory in Java", "description": "Abstract Factory pattern in Java. Full code example in Java with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/abstract-factory-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in Java", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Abstract Factory", "image": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Abstract Factory", "item": "https://refactoring.guru/design-patterns/abstract-factory"}, {"@type": "ListItem", "position": 4, "name": "Java", "item": "https://refactoring.guru/design-patterns/java"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/java/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in Java", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "Java", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Abstract Factory", "Java"], "osnova": [{"uroven": 1, "text": "Abstract Factory in Java"}, {"uroven": 2, "text": "Families of cross-platform GUI components and their production"}, {"uroven": 3, "text": "buttons: First product hierarchy"}, {"uroven": 4, "text": "buttons/Button.java"}, {"uroven": 4, "text": "buttons/MacOSButton.java"}, {"uroven": 4, "text": "buttons/WindowsButton.java"}, {"uroven": 3, "text": "checkboxes: Second product hierarchy"}, {"uroven": 4, "text": "checkboxes/Checkbox.java"}, {"uroven": 4, "text": "checkboxes/MacOSCheckbox.java"}, {"uroven": 4, "text": "checkboxes/WindowsCheckbox.java"}, {"uroven": 3, "text": "factories"}, {"uroven": 4, "text": "factories/GUIFactory.java: Abstract factory"}, {"uroven": 4, "text": "factories/MacOSFactory.java: Concrete factory (macOS)"}, {"uroven": 4, "text": "factories/WindowsFactory.java: Concrete factory (Windows)"}, {"uroven": 3, "text": "app"}, {"uroven": 4, "text": "app/Application.java: Client code"}, {"uroven": 4, "text": "Demo.java: App configuration"}, {"uroven": 4, "text": "OutputDemo.txt: Execution result"}, {"uroven": 2, "text": "Abstract Factory in Other Languages"}], "markdown": "# **Abstract Factory** in Java\n\n**Abstract Factory** is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.\n\nAbstract Factory defines an interface for creating all distinct products but leaves the actual product creation to concrete factory classes. Each factory type corresponds to a certain product variety.\n\nThe client code calls the creation methods of a factory object instead of creating products directly with a constructor call (`new` operator). Since a factory corresponds to a single product variant, all its products will be compatible.\n\nClient code works with factories and products only through their abstract interfaces. This lets the client code work with any product variants, created by the factory object. You just create a new concrete factory class and pass it to the client code.\n\n> If you can’t figure out the difference between various factory patterns and concepts, then read our [Factory Comparison](/design-patterns/factory-comparison).\n\n[Learn more about Abstract Factory](/design-patterns/abstract-factory)\n\n**Complexity:**\n\n**Popularity:**\n\n**Usage examples:** The Abstract Factory pattern is pretty common in Java code. Many frameworks and libraries use it to provide a way to extend and customize their standard components.\n\nHere are some examples from core Java libraries:\n\n- [`javax.xml.parsers.DocumentBuilderFactory#newInstance()`](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#newInstance--)\n- [`javax.xml.transform.TransformerFactory#newInstance()`](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)\n- [`javax.xml.xpath.XPathFactory#newInstance()`](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)\n\n**Identification:** The pattern is easy to recognize by methods, which return a factory object. Then, the factory is used for creating specific sub-components.\n\n## Families of cross-platform GUI components and their production\n\nIn this example, buttons and checkboxes will act as products. They have two variants: macOS and Windows.\n\nThe abstract factory defines an interface for creating buttons and checkboxes. There are two concrete factories, which return both products in a single variant.\n\nClient code works with factories and products using abstract interfaces. It makes the same client code working with many product variants, depending on the type of factory object.\n\n### **buttons:** First product hierarchy\n\n#### **buttons/Button.java**\n\n```\npackage refactoring_guru.abstract_factory.example.buttons;\n\n/**\n * Abstract Factory assumes that you have several families of products,\n * structured into separate class hierarchies (Button/Checkbox). All products of\n * the same family have the common interface.\n *\n * This is the common interface for buttons family.\n */\npublic interface Button {\n void paint();\n}\n```\n\n#### **buttons/MacOSButton.java**\n\n```\npackage refactoring_guru.abstract_factory.example.buttons;\n\n/**\n * All products families have the same varieties (MacOS/Windows).\n *\n * This is a MacOS variant of a button.\n */\npublic class MacOSButton implements Button {\n\n @Override\n public void paint() {\n System.out.println(\"You have created MacOSButton.\");\n }\n}\n```\n\n#### **buttons/WindowsButton.java**\n\n```\npackage refactoring_guru.abstract_factory.example.buttons;\n\n/**\n * All products families have the same varieties (MacOS/Windows).\n *\n * This is another variant of a button.\n */\npublic class WindowsButton implements Button {\n\n @Override\n public void paint() {\n System.out.println(\"You have created WindowsButton.\");\n }\n}\n```\n\n### **checkboxes:** Second product hierarchy\n\n#### **checkboxes/Checkbox.java**\n\n```\npackage refactoring_guru.abstract_factory.example.checkboxes;\n\n/**\n * Checkboxes is the second product family. It has the same variants as buttons.\n */\npublic interface Checkbox {\n void paint();\n}\n```\n\n#### **checkboxes/MacOSCheckbox.java**\n\n```\npackage refactoring_guru.abstract_factory.example.checkboxes;\n\n/**\n * All products families have the same varieties (MacOS/Windows).\n *\n * This is a variant of a checkbox.\n */\npublic class MacOSCheckbox implements Checkbox {\n\n @Override\n public void paint() {\n System.out.println(\"You have created MacOSCheckbox.\");\n }\n}\n```\n\n#### **checkboxes/WindowsCheckbox.java**\n\n```\npackage refactoring_guru.abstract_factory.example.checkboxes;\n\n/**\n * All products families have the same varieties (MacOS/Windows).\n *\n * This is another variant of a checkbox.\n */\npublic class WindowsCheckbox implements Checkbox {\n\n @Override\n public void paint() {\n System.out.println(\"You have created WindowsCheckbox.\");\n }\n}\n```\n\n### **factories**\n\n#### **factories/GUIFactory.java:** Abstract factory\n\n```\npackage refactoring_guru.abstract_factory.example.factories;\n\nimport refactoring_guru.abstract_factory.example.buttons.Button;\nimport refactoring_guru.abstract_factory.example.checkboxes.Checkbox;\n\n/**\n * Abstract factory knows about all (abstract) product types.\n */\npublic interface GUIFactory {\n Button createButton();\n Checkbox createCheckbox();\n}\n```\n\n#### **factories/MacOSFactory.java:** Concrete factory (macOS)\n\n```\npackage refactoring_guru.abstract_factory.example.factories;\n\nimport refactoring_guru.abstract_factory.example.buttons.Button;\nimport refactoring_guru.abstract_factory.example.buttons.MacOSButton;\nimport refactoring_guru.abstract_factory.example.checkboxes.Checkbox;\nimport refactoring_guru.abstract_factory.example.checkboxes.MacOSCheckbox;\n\n/**\n * Each concrete factory extends basic factory and responsible for creating\n * products of a single variety.\n */\npublic class MacOSFactory implements GUIFactory {\n\n @Override\n public Button createButton() {\n return new MacOSButton();\n }\n\n @Override\n public Checkbox createCheckbox() {\n return new MacOSCheckbox();\n }\n}\n```\n\n#### **factories/WindowsFactory.java:** Concrete factory (Windows)\n\n```\npackage refactoring_guru.abstract_factory.example.factories;\n\nimport refactoring_guru.abstract_factory.example.buttons.Button;\nimport refactoring_guru.abstract_factory.example.buttons.WindowsButton;\nimport refactoring_guru.abstract_factory.example.checkboxes.Checkbox;\nimport refactoring_guru.abstract_factory.example.checkboxes.WindowsCheckbox;\n\n/**\n * Each concrete factory extends basic factory and responsible for creating\n * products of a single variety.\n */\npublic class WindowsFactory implements GUIFactory {\n\n @Override\n public Button createButton() {\n return new WindowsButton();\n }\n\n @Override\n public Checkbox createCheckbox() {\n return new WindowsCheckbox();\n }\n}\n```\n\n### **app**\n\n#### **app/Application.java:** Client code\n\n```\npackage refactoring_guru.abstract_factory.example.app;\n\nimport refactoring_guru.abstract_factory.example.buttons.Button;\nimport refactoring_guru.abstract_factory.example.checkboxes.Checkbox;\nimport refactoring_guru.abstract_factory.example.factories.GUIFactory;\n\n/**\n * Factory users don't care which concrete factory they use since they work with\n * factories and products through abstract interfaces.\n */\npublic class Application {\n private Button button;\n private Checkbox checkbox;\n\n public Application(GUIFactory factory) {\n button = factory.createButton();\n checkbox = factory.createCheckbox();\n }\n\n public void paint() {\n button.paint();\n checkbox.paint();\n }\n}\n```\n\n#### **Demo.java:** App configuration\n\n```\npackage refactoring_guru.abstract_factory.example;\n\nimport refactoring_guru.abstract_factory.example.app.Application;\nimport refactoring_guru.abstract_factory.example.factories.GUIFactory;\nimport refactoring_guru.abstract_factory.example.factories.MacOSFactory;\nimport refactoring_guru.abstract_factory.example.factories.WindowsFactory;\n\n/**\n * Demo class. Everything comes together here.\n */\npublic class Demo {\n\n /**\n * Application picks the factory type and creates it in run time (usually at\n * initialization stage), depending on the configuration or environment\n * variables.\n */\n private static Application configureApplication() {\n Application app;\n GUIFactory factory;\n String osName = System.getProperty(\"os.name\").toLowerCase();\n if (osName.contains(\"mac\")) {\n factory = new MacOSFactory();\n } else {\n factory = new WindowsFactory();\n }\n app = new Application(factory);\n return app;\n }\n\n public static void main(String[] args) {\n Application app = configureApplication();\n app.paint();\n }\n}\n```\n\n#### **OutputDemo.txt:** Execution result\n\n```\nYou create WindowsButton.\nYou created WindowsCheckbox.\n```\n\n## **Abstract Factory** in Other Languages", "znaku_textu": 8248, "slov": 862, "odkazu": 208, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:03", "sha256": "f86c27a38af23d95299d1e77e9047266fed225e1f0a08df547387e86a50d0e46", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html", "http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html", "http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/abstract-factory/java/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]} {"url": "https://refactoring.guru/design-patterns/abstract-factory/php/example", "titulek": "Abstract Factory in PHP / Design Patterns", "h1": "Abstract Factory in PHP", "popis": "Abstract Factory pattern in PHP. Full code example in PHP with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/abstract-factory/php/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#webpage", "url": "https://refactoring.guru/design-patterns/abstract-factory/php/example", "inLanguage": "en", "name": "Abstract Factory in PHP", "description": "Abstract Factory pattern in PHP. Full code example in PHP with detailed comments and explanation. Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/abstract-factory-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in PHP", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Abstract Factory", "image": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Abstract Factory", "item": "https://refactoring.guru/design-patterns/abstract-factory"}, {"@type": "ListItem", "position": 4, "name": "PHP", "item": "https://refactoring.guru/design-patterns/php"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/abstract-factory/php/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Abstract Factory in PHP", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "PHP", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Abstract Factory", "PHP"], "osnova": [{"uroven": 1, "text": "Abstract Factory in PHP"}, {"uroven": 2, "text": "Conceptual Example"}, {"uroven": 4, "text": "index.php: Conceptual example"}, {"uroven": 4, "text": "Output.txt: Execution result"}, {"uroven": 2, "text": "Real World Example"}, {"uroven": 4, "text": "index.php: Real world example"}, {"uroven": 4, "text": "Output.txt: Execution result"}, {"uroven": 2, "text": "Abstract Factory in Other Languages"}], "markdown": "# **Abstract Factory** in PHP\n\n**Abstract Factory** is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.\n\nAbstract Factory defines an interface for creating all distinct products but leaves the actual product creation to concrete factory classes. Each factory type corresponds to a certain product variety.\n\nThe client code calls the creation methods of a factory object instead of creating products directly with a constructor call (`new` operator). Since a factory corresponds to a single product variant, all its products will be compatible.\n\nClient code works with factories and products only through their abstract interfaces. This lets the client code work with any product variants, created by the factory object. You just create a new concrete factory class and pass it to the client code.\n\n> If you can’t figure out the difference between various factory patterns and concepts, then read our [Factory Comparison](/design-patterns/factory-comparison).\n\n[Learn more about Abstract Factory](/design-patterns/abstract-factory)\n\n**Complexity:**\n\n**Popularity:**\n\n**Usage examples:** The Abstract Factory pattern is pretty common in PHP code. Many frameworks and libraries use it to provide a way to extend and customize their standard components.\n\n**Identification:** The pattern is easy to recognize by methods, which return a factory object. Then, the factory is used for creating specific sub-components.\n\n## Conceptual Example\n\nThis example illustrates the structure of the **Abstract Factory** design pattern. It focuses on answering these questions:\n\n- What classes does it consist of?\n- What roles do these classes play?\n- In what way the elements of the pattern are related?\n\nAfter learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real-world PHP use case.\n\n#### **index.php:** Conceptual example\n\n```\nusefulFunctionA();\n\n return \"The result of the B1 collaborating with the ({$result})\";\n }\n}\n\nclass ConcreteProductB2 implements AbstractProductB\n{\n public function usefulFunctionB(): string\n {\n return \"The result of the product B2.\";\n }\n\n /**\n * The variant, Product B2, is only able to work correctly with the variant,\n * Product A2. Nevertheless, it accepts any instance of AbstractProductA as\n * an argument.\n */\n public function anotherUsefulFunctionB(AbstractProductA $collaborator): string\n {\n $result = $collaborator->usefulFunctionA();\n\n return \"The result of the B2 collaborating with the ({$result})\";\n }\n}\n\n/**\n * The client code works with factories and products only through abstract\n * types: AbstractFactory and AbstractProduct. This lets you pass any factory or\n * product subclass to the client code without breaking it.\n */\nfunction clientCode(AbstractFactory $factory)\n{\n $productA = $factory->createProductA();\n $productB = $factory->createProductB();\n\n echo $productB->usefulFunctionB() . \"\\n\";\n echo $productB->anotherUsefulFunctionB($productA) . \"\\n\";\n}\n\n/**\n * The client code can work with any concrete factory class.\n */\necho \"Client: Testing client code with the first factory type:\\n\";\nclientCode(new ConcreteFactory1());\n\necho \"\\n\";\n\necho \"Client: Testing the same client code with the second factory type:\\n\";\nclientCode(new ConcreteFactory2());\n```\n\n#### **Output.txt:** Execution result\n\n```\nClient: Testing client code with the first factory type:\nThe result of the product B1.\nThe result of the B1 collaborating with the (The result of the product A1.)\n\nClient: Testing the same client code with the second factory type:\nThe result of the product B2.\nThe result of the B2 collaborating with the (The result of the product A2.)\n```\n\n## Real World Example\n\nIn this example, the **Abstract Factory** pattern provides an infrastructure for creating various types of templates for different elements of a web page.\n\nA web application can support different rendering engines at the same time, but only if its classes are independent of the concrete classes of rendering engines. Hence, the application’s objects must communicate with template objects only via their abstract interfaces. Your code shouldn’t create the template objects directly, but delegate their creation to special factory objects. Finally, your code shouldn’t depend on the factory objects either but, instead, should work with them via the abstract factory interface.\n\nAs a result, you will be able to provide the app with the factory object that corresponds to one of the rendering engines. All templates, created in the app, will be created by that factory and their type will match the type of the factory. If you decide to change the rendering engine, you’ll be able to pass a new factory to the client code, without breaking any existing code.\n\n#### **index.php:** Real world example\n\n```\ncreateTitleTemplate());\n }\n\n public function getRenderer(): TemplateRenderer\n {\n return new TwigRenderer();\n }\n}\n\n/**\n * And this Concrete Factory creates PHPTemplate templates.\n */\nclass PHPTemplateFactory implements TemplateFactory\n{\n public function createTitleTemplate(): TitleTemplate\n {\n return new PHPTemplateTitleTemplate();\n }\n\n public function createPageTemplate(): PageTemplate\n {\n return new PHPTemplatePageTemplate($this->createTitleTemplate());\n }\n\n public function getRenderer(): TemplateRenderer\n {\n return new PHPTemplateRenderer();\n }\n}\n\n/**\n * Each distinct product type should have a separate interface. All variants of\n * the product must follow the same interface.\n *\n * For instance, this Abstract Product interface describes the behavior of page\n * title templates.\n */\ninterface TitleTemplate\n{\n public function getTemplateString(): string;\n}\n\n/**\n * This Concrete Product provides Twig page title templates.\n */\nclass TwigTitleTemplate implements TitleTemplate\n{\n public function getTemplateString(): string\n {\n return \"
\nAdd to cart\n\n\nJSON view of a simple content page, with the same client code:\n{\n\"title\": \"Star Wars, episode1\",\n\"text\": \"A long time ago in a galaxy far, far away...\",\n\"img\": \"/images/star-wars.jpeg\",\n\"link\": {\"href\": \"/cart/add/123\", \"title\": \"Add to cart\"}\n}\n```\n\n## **Bridge** in Other Languages", "znaku_textu": 11324, "slov": 1516, "odkazu": 198, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:29", "sha256": "52b8fa4f30822d42ab8096c1429cfd4341d3fac50bb6eb980ed9c42bffe9160b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/bridge/php/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]}
{"url": "https://refactoring.guru/design-patterns/bridge/python/example", "titulek": "Bridge in Python / Design Patterns", "h1": "Bridge in Python", "popis": "Bridge pattern in Python. Full code example in Python with detailed comments and explanation. Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/bridge/python/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/bridge/python/example#webpage", "url": "https://refactoring.guru/design-patterns/bridge/python/example", "inLanguage": "en", "name": "Bridge in Python", "description": "Bridge pattern in Python. Full code example in Python with detailed comments and explanation. Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/bridge/python/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/bridge-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/bridge/python/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Bridge in Python", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Bridge", "image": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/bridge/python/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Bridge", "item": "https://refactoring.guru/design-patterns/bridge"}, {"@type": "ListItem", "position": 4, "name": "Python", "item": "https://refactoring.guru/design-patterns/python"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/bridge/python/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/python/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Bridge in Python", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "Python", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Bridge", "Python"], "osnova": [{"uroven": 1, "text": "Bridge in Python"}, {"uroven": 2, "text": "Conceptual Example"}, {"uroven": 4, "text": "main.py: Conceptual example"}, {"uroven": 4, "text": "Output.txt: Execution result"}, {"uroven": 2, "text": "Bridge in Other Languages"}], "markdown": "# **Bridge** in Python\n\n**Bridge** is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.\n\nOne of these hierarchies (often called the Abstraction) will get a reference to an object of the second hierarchy (Implementation). The abstraction will be able to delegate some (sometimes, most) of its calls to the implementations object. Since all implementations will have a common interface, they’d be interchangeable inside the abstraction.\n\n[Learn more about Bridge](/design-patterns/bridge)\n\n**Complexity:**\n\n**Popularity:**\n\n**Usage examples:** The Bridge pattern is especially useful when dealing with cross-platform apps, supporting multiple types of database servers or working with several API providers of a certain kind (for example, cloud platforms, social networks, etc.)\n\n**Identification:** Bridge can be recognized by a clear distinction between some controlling entity and several different platforms that it relies on.\n\n## Conceptual Example\n\nThis example illustrates the structure of the **Bridge** design pattern. It focuses on answering these questions:\n\n- What classes does it consist of?\n- What roles do these classes play?\n- In what way the elements of the pattern are related?\n\n#### **main.py:** Conceptual example\n\n```\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\n\nclass Abstraction:\n \"\"\"\n The Abstraction defines the interface for the \"control\" part of the two\n class hierarchies. It maintains a reference to an object of the\n Implementation hierarchy and delegates all of the real work to this object.\n \"\"\"\n\n def __init__(self, implementation: Implementation) -> None:\n self.implementation = implementation\n\n def operation(self) -> str:\n return (f\"Abstraction: Base operation with:\\n\"\n f\"{self.implementation.operation_implementation()}\")\n\nclass ExtendedAbstraction(Abstraction):\n \"\"\"\n You can extend the Abstraction without changing the Implementation classes.\n \"\"\"\n\n def operation(self) -> str:\n return (f\"ExtendedAbstraction: Extended operation with:\\n\"\n f\"{self.implementation.operation_implementation()}\")\n\nclass Implementation(ABC):\n \"\"\"\n The Implementation defines the interface for all implementation classes. It\n doesn't have to match the Abstraction's interface. In fact, the two\n interfaces can be entirely different. Typically the Implementation interface\n provides only primitive operations, while the Abstraction defines higher-\n level operations based on those primitives.\n \"\"\"\n\n @abstractmethod\n def operation_implementation(self) -> str:\n pass\n\n\"\"\"\nEach Concrete Implementation corresponds to a specific platform and implements\nthe Implementation interface using that platform's API.\n\"\"\"\n\nclass ConcreteImplementationA(Implementation):\n def operation_implementation(self) -> str:\n return \"ConcreteImplementationA: Here's the result on the platform A.\"\n\nclass ConcreteImplementationB(Implementation):\n def operation_implementation(self) -> str:\n return \"ConcreteImplementationB: Here's the result on the platform B.\"\n\ndef client_code(abstraction: Abstraction) -> None:\n \"\"\"\n Except for the initialization phase, where an Abstraction object gets linked\n with a specific Implementation object, the client code should only depend on\n the Abstraction class. This way the client code can support any abstraction-\n implementation combination.\n \"\"\"\n\n # ...\n\n print(abstraction.operation(), end=\"\")\n\n # ...\n\nif __name__ == \"__main__\":\n \"\"\"\n The client code should be able to work with any pre-configured abstraction-\n implementation combination.\n \"\"\"\n\n implementation = ConcreteImplementationA()\n abstraction = Abstraction(implementation)\n client_code(abstraction)\n\n print(\"\\n\")\n\n implementation = ConcreteImplementationB()\n abstraction = ExtendedAbstraction(implementation)\n client_code(abstraction)\n```\n\n#### **Output.txt:** Execution result\n\n```\nAbstraction: Base operation with:\nConcreteImplementationA: Here's the result on the platform A.\n\nExtendedAbstraction: Extended operation with:\nConcreteImplementationB: Here's the result on the platform B.\n```\n\n## **Bridge** in Other Languages", "znaku_textu": 4017, "slov": 487, "odkazu": 195, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:29", "sha256": "5d30da71e2bb19d6265610bc67fc35f8b5bb4e47b11d90acd0cc971721110b80", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/bridge/python/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]}
{"url": "https://refactoring.guru/design-patterns/bridge/ruby/example", "titulek": "Bridge in Ruby / Design Patterns", "h1": "Bridge in Ruby", "popis": "Bridge pattern in Ruby. Full code example in Ruby with detailed comments and explanation. Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/bridge/ruby/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#webpage", "url": "https://refactoring.guru/design-patterns/bridge/ruby/example", "inLanguage": "en", "name": "Bridge in Ruby", "description": "Bridge pattern in Ruby. Full code example in Ruby with detailed comments and explanation. Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/bridge-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Bridge in Ruby", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Bridge", "image": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Bridge", "item": "https://refactoring.guru/design-patterns/bridge"}, {"@type": "ListItem", "position": 4, "name": "Ruby", "item": "https://refactoring.guru/design-patterns/ruby"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/ruby/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Bridge in Ruby", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "Ruby", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Bridge", "Ruby"], "osnova": [{"uroven": 1, "text": "Bridge in Ruby"}, {"uroven": 2, "text": "Conceptual Example"}, {"uroven": 4, "text": "main.rb: Conceptual example"}, {"uroven": 4, "text": "output.txt: Execution result"}, {"uroven": 2, "text": "Bridge in Other Languages"}], "markdown": "# **Bridge** in Ruby\n\n**Bridge** is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.\n\nOne of these hierarchies (often called the Abstraction) will get a reference to an object of the second hierarchy (Implementation). The abstraction will be able to delegate some (sometimes, most) of its calls to the implementations object. Since all implementations will have a common interface, they’d be interchangeable inside the abstraction.\n\n[Learn more about Bridge](/design-patterns/bridge)\n\n**Complexity:**\n\n**Popularity:**\n\n**Usage examples:** The Bridge pattern is especially useful when dealing with cross-platform apps, supporting multiple types of database servers or working with several API providers of a certain kind (for example, cloud platforms, social networks, etc.)\n\n**Identification:** Bridge can be recognized by a clear distinction between some controlling entity and several different platforms that it relies on.\n\n## Conceptual Example\n\nThis example illustrates the structure of the **Bridge** design pattern. It focuses on answering these questions:\n\n- What classes does it consist of?\n- What roles do these classes play?\n- In what way the elements of the pattern are related?\n\n#### **main.rb:** Conceptual example\n\n```\n# The Abstraction defines the interface for the \"control\" part of the two class\n# hierarchies. It maintains a reference to an object of the Implementation\n# hierarchy and delegates all of the real work to this object.\nclass Abstraction\n # @param [Implementation] implementation\n def initialize(implementation)\n @implementation = implementation\n end\n\n # @return [String]\n def operation\n \"Abstraction: Base operation with:\\n\"\\\n \"#{@implementation.operation_implementation}\"\n end\nend\n\n# You can extend the Abstraction without changing the Implementation classes.\nclass ExtendedAbstraction < Abstraction\n # @return [String]\n def operation\n \"ExtendedAbstraction: Extended operation with:\\n\"\\\n \"#{@implementation.operation_implementation}\"\n end\nend\n\n# The Implementation defines the interface for all implementation classes. It\n# doesn't have to match the Abstraction's interface. In fact, the two interfaces\n# can be entirely different. Typically the Implementation interface provides\n# only primitive operations, while the Abstraction defines higher-level\n# operations based on those primitives.\nclass Implementation\n # @abstract\n #\n # @return [String]\n def operation_implementation\n raise NotImplementedError, \"#{self.class} has not implemented method '#{__method__}'\"\n end\nend\n\n# Each Concrete Implementation corresponds to a specific platform and implements\n# the Implementation interface using that platform's API.\nclass ConcreteImplementationA < Implementation\n # @return [String]\n def operation_implementation\n 'ConcreteImplementationA: Here\\'s the result on the platform A.'\n end\nend\n\nclass ConcreteImplementationB < Implementation\n # @return [String]\n def operation_implementation\n 'ConcreteImplementationB: Here\\'s the result on the platform B.'\n end\nend\n\n# Except for the initialization phase, where an Abstraction object gets linked\n# with a specific Implementation object, the client code should only depend on\n# the Abstraction class. This way the client code can support any abstraction-\n# implementation combination.\ndef client_code(abstraction)\n # ...\n\n print abstraction.operation\n\n # ...\nend\n\n# The client code should be able to work with any pre-configured abstraction-\n# implementation combination.\n\nimplementation = ConcreteImplementationA.new\nabstraction = Abstraction.new(implementation)\nclient_code(abstraction)\n\nputs \"\\n\\n\"\n\nimplementation = ConcreteImplementationB.new\nabstraction = ExtendedAbstraction.new(implementation)\nclient_code(abstraction)\n```\n\n#### **output.txt:** Execution result\n\n```\nAbstraction: Base operation with:\nConcreteImplementationA: Here's the result on the platform A.\n\nExtendedAbstraction: Extended operation with:\nConcreteImplementationB: Here's the result on the platform B.\n```\n\n## **Bridge** in Other Languages", "znaku_textu": 3962, "slov": 491, "odkazu": 193, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 21:27:30", "sha256": "03c37dfd381178375ca40d10a54d1b7c4f24a08a98ccce061494a0e51e16154b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://gitbybit.com/", "https://feedback.refactoring.guru/", "https://refactoringguru.cn/design-patterns/bridge/ruby/example", "https://feedback.refactoring.guru/?show_feedback_form_private=true", "https://refactoring.userecho.com/", "https://www.facebook.com/refactoring.guru", "https://github.com/RefactoringGuru", "http://zhart.us/"]}
{"url": "https://refactoring.guru/design-patterns/bridge/rust/example", "titulek": "Bridge in Rust / Design Patterns", "h1": "Bridge in Rust", "popis": "Bridge pattern in Rust. Full code example in Rust with detailed comments and explanation. Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.", "klicova_slova": "", "kanonicka": "https://refactoring.guru/design-patterns/bridge/rust/example", "jazyk": "en", "robots_meta": "", "og": {"og:type": "website", "og:image": "https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868"}, "jsonld": [{"@context": "http://schema.org", "@graph": [{"@type": "Person", "@id": "https://refactoring.guru/#founder", "name": "Alexander Shvets"}, {"@type": "Organization", "@id": "https://refactoring.guru/#organization", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/#organizationlogo", "url": "https://refactoring.guru/images/content-public/logos/logo-plain.png", "caption": "Refactoring.Guru"}, "logo": {"@id": "https://refactoring.guru/#organizationlogo"}, "founder": {"@id": "https://refactoring.guru/#founder"}, "sameAs": ["https://www.facebook.com/refactoring.guru", "https://twitter.com/RefactoringGuru", "https://github.com/RefactoringGuru"]}, {"@type": "WebSite", "@id": "https://refactoring.guru/#website", "url": "https://refactoring.guru/", "name": "Refactoring.Guru", "description": "Refactoring.Guru makes it easy for you to discover everything you need to know about refactoring, design patterns, SOLID principles, and other smart programming topics.", "author": {"@id": "https://refactoring.guru/#founder"}, "publisher": {"@id": "https://refactoring.guru/#organization"}, "copyrightYear": 2014}, {"@type": "WebPage", "@id": "https://refactoring.guru/design-patterns/bridge/rust/example#webpage", "url": "https://refactoring.guru/design-patterns/bridge/rust/example", "inLanguage": "en", "name": "Bridge in Rust", "description": "Bridge pattern in Rust. Full code example in Rust with detailed comments and explanation. Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.", "isPartOf": {"@id": "https://refactoring.guru#website"}, "breadcrumb": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#breadcrumb"}, "primaryImageOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#primaryimage"}, "image": {"@type": "ImageObject", "@id": "https://refactoring.guru/design-patterns/bridge/rust/example#primaryimage", "url": "https://refactoring.guru/images/patterns/cards/bridge-mini-3x.png", "width": 420, "height": 300}}, {"@type": "Article", "@id": "https://refactoring.guru/design-patterns/bridge/rust/example#article", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Bridge in Rust", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "articleSection": "Bridge", "image": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#primaryimage"}}, {"@type": "BreadcrumbList", "@id": "https://refactoring.guru/design-patterns/bridge/rust/example#breadcrumb", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://refactoring.guru"}, {"@type": "ListItem", "position": 2, "name": "Design Patterns", "item": "https://refactoring.guru/design-patterns"}, {"@type": "ListItem", "position": 3, "name": "Bridge", "item": "https://refactoring.guru/design-patterns/bridge"}, {"@type": "ListItem", "position": 4, "name": "Rust", "item": "https://refactoring.guru/design-patterns/rust"}]}, {"@type": "SoftwareSourceCode", "@id": "https://refactoring.guru/design-patterns/bridge/rust/example#code", "isPartOf": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#webpage"}, "mainEntityOfPage": {"@id": "https://refactoring.guru/design-patterns/bridge/rust/example#webpage"}, "author": {"@id": "https://refactoring.guru#founder"}, "publisher": {"@id": "https://refactoring.guru#organization"}, "headline": "Bridge in Rust", "datePublished": "2025-01-01", "dateModified": "2026-01-01", "programmingLanguage": "Rust", "codeSampleType": "full"}]}], "drobecky": ["Home", "Design Patterns", "Bridge", "Rust"], "osnova": [{"uroven": 1, "text": "Bridge in Rust"}, {"uroven": 2, "text": "Devices and Remotes"}, {"uroven": 4, "text": "remotes/mod.rs"}, {"uroven": 4, "text": "remotes/basic.rs"}, {"uroven": 4, "text": "remotes/advanced.rs"}, {"uroven": 4, "text": "device/mod.rs"}, {"uroven": 4, "text": "device/radio.rs"}, {"uroven": 4, "text": "device/tv.rs"}, {"uroven": 4, "text": "main.rs"}, {"uroven": 3, "text": "Output"}, {"uroven": 2, "text": "Bridge in Other Languages"}], "markdown": "# **Bridge** in Rust\n\n**Bridge** is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently.\n\nOne of these hierarchies (often called the Abstraction) will get a reference to an object of the second hierarchy (Implementation). The abstraction will be able to delegate some (sometimes, most) of its calls to the implementations object. Since all implementations will have a common interface, they’d be interchangeable inside the abstraction.\n\n[Learn more about Bridge](/design-patterns/bridge)\n\n## Devices and Remotes\n\nThis example illustrates how the Bridge pattern can help divide the monolithic code of an app that manages devices and their remote controls. The Device classes act as the implementation, whereas the Remotes act as the abstraction.\n\n#### **remotes/mod.rs**\n\n```\nmod advanced;\nmod basic;\n\npub use advanced::AdvancedRemote;\npub use basic::BasicRemote;\n\nuse crate::device::Device;\n\npub trait HasMutableDevice