### Ruby Builder Pattern Example Source: https://refactoring.guru/design-patterns/builder/ruby/example Demonstrates the Builder pattern in Ruby. It shows how a Director class guides the construction of a product by a ConcreteBuilder, creating both minimal and full-featured products. It also illustrates building a custom product directly using builder methods. ```ruby class Director attr_writer :builder def build_minimal_viable_product @builder.produce_part_a end def build_full_featured_product @builder.produce_part_a @builder.produce_part_b @builder.produce_part_c end end class Builder attr_accessor :reset def produce_part_a # Abstract method end def produce_part_b # Abstract method end def produce_part_c # Abstract method end end class ConcreteBuilder1 < Builder def initialize reset end def reset @product = Product1.new @product end def produce_part_a @product.add('PartA1') end def produce_part_b @product.add('PartB1') end def produce_part_c @product.add('PartC1') end def product product = @product reset product end end class Product1 def initialize @parts = [] end def add(part) @parts << part end def list_parts puts "Product parts: #{@parts.join(', ')}" end end director = Director.new builder = ConcreteBuilder1.new director.builder = builder puts 'Standard basic product: ' director.build_minimal_viable_product puts builder.product.list_parts puts "\n\n" puts 'Standard full featured product: ' director.build_full_featured_product puts builder.product.list_parts puts "\n\n" # Remember, the Builder pattern can be used without a Director class. puts 'Custom product: ' builder.produce_part_a builder.produce_part_b puts builder.product.list_parts ``` -------------------------------- ### Facade Pattern Conceptual Example Output in Text Source: https://refactoring.guru/design-patterns/facade/swift/example Provides the expected output when the conceptual Facade pattern example in Swift is executed. It shows the simplified interaction initiated by the Facade, which then orchestrates operations within the subsystems. ```text Facade initializes subsystems: Sybsystem1: Ready! Sybsystem2: Get ready! Facade orders subsystems to perform the action: Sybsystem1: Go! Sybsystem2: Fire! ``` -------------------------------- ### Factory Method Swift Example Output Source: https://refactoring.guru/design-patterns/factory-method/swift/example The output generated by the Swift Factory Method example, illustrating how information is presented over different network types (Wifi and Bluetooth) using the respective projectors. ```text Info is presented over Wifi: Very important info of the presentation Info is presented over Bluetooth: Very important info of the presentation ``` -------------------------------- ### Template Method Pattern Swift Example Output Source: https://refactoring.guru/design-patterns/template-method/swift/example This output shows the result of executing the Swift example for the Template Method pattern. It indicates whether access was granted or denied for Camera, Microphone, and PhotoLibrary, along with analytics messages for PhotoLibrary. ```text You have access to Camera You have access to Microphone PhotoLibrary Accessor: Rejected with access. Updating analytics... You do not have access to PhotoLibrary ``` -------------------------------- ### Go Main Function for Adapter Pattern Demonstration Source: https://refactoring.guru/design-patterns/adapter/go/example The main function orchestrates the example, demonstrating the direct use of the Mac service and the use of the WindowsAdapter to make the Windows machine compatible. ```Go package main func main() { client := &Client{} mac := &Mac{} client.InsertLightningConnectorIntoComputer(mac) windowsMachine := &Windows{} windowsMachineAdapter := &WindowsAdapter{ windowMachine: windowsMachine, } client.InsertLightningConnectorIntoComputer(windowsMachineAdapter) } ``` -------------------------------- ### Client Code Example in Rust Source: https://refactoring.guru/design-patterns/factory-method/rust/example The `main` function serves as the client code that utilizes the Factory Method pattern. It calls the `initialize` function to get a `Dialog` object and then uses its `render` and `refresh` methods, demonstrating that the client code works with the abstract `Dialog` trait. ```rust mod gui; mod html_gui; mod init; mod windows_gui; use init::initialize; fn main() { // The rest of the code doesn't depend on specific dialog types, because // it works with all dialog objects via the abstract `Dialog` trait // which is defined in the `gui` module. let dialog = initialize(); dialog.render(); dialog.refresh(); } ``` -------------------------------- ### Java: Demo Application for Text Editor Source: https://refactoring.guru/design-patterns/command/java/example Provides the main entry point for the text editor application. It instantiates and initializes the `Editor` class, which sets up the GUI and command handling. ```java package refactoring_guru.command.example; import refactoring_guru.command.example.editor.Editor; public class Demo { public static void main(String[] args) { Editor editor = new Editor(); editor.init(); } } ``` -------------------------------- ### PHP Singleton Pattern Execution Result Source: https://refactoring.guru/design-patterns/singleton/php/example This section displays the output generated by the execution of the PHP Singleton pattern example. It shows the log messages indicating the start and end of the process, confirmation of the Logger having a single instance, and successful retrieval of configuration values, demonstrating the pattern's functionality. ```text 2018-06-04: Started! 2018-06-04: Logger has a single instance. 2018-06-04: Config singleton also works fine. 2018-06-04: Finished! ``` -------------------------------- ### Client Code for Prototype Pattern in Go Source: https://refactoring.guru/design-patterns/prototype/go/example Demonstrates the usage of the Prototype pattern by creating file and folder objects, printing their initial hierarchy, cloning the main folder, and then printing the cloned hierarchy. Requires the `fmt` package for output. ```go package main import "fmt" func main() { file1 := &File{name: "File1"} file2 := &File{name: "File2"} file3 := &File{name: "File3"} folder1 := &Folder{ children: []Inode{file1}, name: "Folder1", } folder2 := &Folder{ children: []Inode{folder1, file2, file3}, name: "Folder2", } fmt.Println("\nPrinting hierarchy for Folder2") folder2.print(" ") cloneFolder := folder2.clone() fmt.Println("\nPrinting hierarchy for clone Folder") cloneFolder.print(" ") } ``` -------------------------------- ### Client Code (Main) in Go Source: https://refactoring.guru/design-patterns/command/go/example The client code in Go sets up the Command objects, associates them with Receivers, and configures the Invokers. It demonstrates how to use the Command pattern to trigger actions. ```go package main func main() { tv := &Tv{} onCommand := &OnCommand{ device: tv, } offCommand := &OffCommand{ device: tv, } onButton := &Button{ command: onCommand, } onButton.press() offButton := &Button{ command: offCommand, } offButton.press() } ``` -------------------------------- ### Conceptual Example of Command Pattern in PHP Source: https://refactoring.guru/design-patterns/command/php/example This PHP code demonstrates the conceptual example of the Command design pattern. It defines the Command interface, concrete command classes (SimpleCommand and ComplexCommand), a Receiver class, and an Invoker class. The example illustrates how to encapsulate requests and delegate them to receivers, showcasing the pattern's structure and relationships. ```php payload = $payload; } public function execute(): void { echo "SimpleCommand: See, I can do simple things like printing (" . $this->payload . ")\n"; } } /** * However, some commands can delegate more complex operations to other objects, * called "receivers." */ class ComplexCommand implements Command { /** * @var Receiver */ private $receiver; /** * Context data, required for launching the receiver's methods. */ private $a; private $b; /** * Complex commands can accept one or several receiver objects along with * any context data via the constructor. */ public function __construct(Receiver $receiver, string $a, string $b) { $this->receiver = $receiver; $this->a = $a; $this->b = $b; } /** * Commands can delegate to any methods of a receiver. */ public function execute(): void { echo "ComplexCommand: Complex stuff should be done by a receiver object.\n"; $this->receiver->doSomething($this->a); $this->receiver->doSomethingElse($this->b); } } /** * The Receiver classes contain some important business logic. They know how to * perform all kinds of operations, associated with carrying out a request. In * fact, any class may serve as a Receiver. */ class Receiver { public function doSomething(string $a): void { echo "Receiver: Working on (" . $a . ".)\n"; } public function doSomethingElse(string $b): void { echo "Receiver: Also working on (" . $b . ".)\n"; } } /** * The Invoker is associated with one or several commands. It sends a request to * the command. */ class Invoker { /** * @var Command */ private $onStart; /** * @var Command */ private $onFinish; /** * Initialize commands. */ public function setOnStart(Command $command): void { $this->onStart = $command; } public function setOnFinish(Command $command): void { $this->onFinish = $command; } /** * The Invoker does not depend on concrete command or receiver classes. The * Invoker passes a request to a receiver indirectly, by executing a * command. */ public function doSomethingImportant(): void { echo "Invoker: Does anybody want something done before I begin?\n"; if ($this->onStart instanceof Command) { $this->onStart->execute(); } echo "Invoker: ...doing something really important...\n"; echo "Invoker: Does anybody want something done after I finish?\n"; if ($this->onFinish instanceof Command) { $this->onFinish->execute(); } } } /** * The client code can parameterize an invoker with any commands. */ $invoker = new Invoker(); $invoker->setOnStart(new SimpleCommand("Say Hi!")); $receiver = new Receiver(); $invoker->setOnFinish(new ComplexCommand($receiver, "Send email", "Save report")); $invoker->doSomethingImportant(); ``` -------------------------------- ### Builder Pattern Implementation in C# Source: https://refactoring.guru/design-patterns/builder/csharp/example Demonstrates the Builder pattern in C#, showing how to construct complex objects through a step-by-step process. This example illustrates building different product configurations and listing their parts. ```csharp namespace RefactoringGuru.DesignPatterns.Creational.Builder.Conceptual { // The Builder interface declares a set of methods for creating parts of a // Product object. All concrete builders implement these methods in order to // produce different representations of the same product. public interface IBuilder { void Reset(); void BuildPartA(); void BuildPartB(); void BuildPartC(); } // The Concrete Builder classes follow the Builder interface and provide // specific implementations of the building steps. Your program may have // several variations of builders, each one implementing the building process // differently. public class ConcreteBuilderA : IBuilder { private Product _product; // A fresh builder instance contains a single product instance and none // of the intermediate results. public ConcreteBuilderA() { this.Reset(); } public void Reset() { this._product = new Product(); } // All production steps work with the same product instance that is // stored in the builder and usually realized through a getter method // in the builder interface. public void BuildPartA() { this._product.Add("PartA1"); } public void BuildPartB() { this._product.Add("PartB1"); } public void BuildPartC() { this._product.Add("PartC1"); } // Concrete Builders are not part of the same interface. Since the client // code can work with any builder, we are not coupling the client code // to the concrete classes of the builders. So, we use the builder // interface to return the final object. public Product GetProduct() { Product result = this._product; this.Reset(); return result; } } public class ConcreteBuilderB : IBuilder { private Product _product; public ConcreteBuilderB() { this.Reset(); } public void Reset() { this._product = new Product(); } public void BuildPartA() { this._product.Add("PartA2"); } // The Concrete Builder B is the same as A, but it does not implement // the BuildPartB() method. That means it produces a different // product than builder A. public void BuildPartB() { this._product.Add("PartB2"); } public void BuildPartC() { this._product.Add("PartC2"); } public Product GetProduct() { Product result = this._product; this.Reset(); return result; } } // The Product is an object that the builder constructs. Products are // often complex objects that require assembly from several parts. // The Builder interface may define a common interface for all. public class Product { private List _parts = new List(); public void Add(string part) { this._parts.Add(part); } public string ListParts() { string s = string.Join(", ", this._parts); return "Product parts: " + s + "\n\n"; } } // The Director class works with the Builder interface. It does not know // about the concrete builder, so it can work with any builder passed to // it. The director only knows the common interface of the builder. // It allows to construct products in a specific order, which may be // different for different product types. public class Director { private IBuilder _builder; public IBuilder Builder { set { _builder = value; } } // The Director can construct multiple variations of a product using // the same template of steps. It can produce different results using // the same set of steps. public void BuildMinimalViableProduct() { this._builder.BuildPartA(); } public void BuildFullFeaturedProduct() { this._builder.BuildPartA(); this._builder.BuildPartB(); this._builder.BuildPartC(); } } class Program { static void Main(string[] args) { // The client code creates a builder object in order to create a // product. The important thing is that the client code can // choose the type of the builder it wants to use. var builder = new ConcreteBuilderA(); var director = new Director(); director.Builder = builder; Console.WriteLine("Standard basic product:"); director.BuildMinimalViableProduct(); Console.Write(builder.GetProduct().ListParts()); Console.WriteLine("Standard full featured product:"); director.BuildFullFeaturedProduct(); Console.Write(builder.GetProduct().ListParts()); // Remember, the Builder pattern can be used without a Director // class. Console.WriteLine("Custom product:"); builder.BuildPartA(); builder.BuildPartC(); Console.Write(builder.GetProduct().ListParts()); } } } ``` -------------------------------- ### Abstract Factory Conceptual Example Source: https://refactoring.guru/design-patterns/abstract-factory/python/example Illustrates the structure of the Abstract Factory design pattern, showing the classes, their roles, and their relationships. This example is language-agnostic in its conceptual explanation. ```text This example illustrates the structure of the **Abstract Factory** design pattern. It focuses on answering these questions: * What classes does it consist of? * What roles do these classes play? * In what way the elements of the pattern are related? ``` -------------------------------- ### Template Method: Client Usage Example (Go) Source: https://refactoring.guru/design-patterns/template-method/go/example Demonstrates how to use the Template Method pattern in a client application. It initializes instances of the concrete implementations (`Sms` and `Email`) and then uses the base `Otp` struct to execute the `genAndSendOTP` method, showing polymorphism in action. The `main` function sets up and runs the OTP sending process for both SMS and Email. ```go package main import "fmt" func main() { smsOTP := &Sms{} o := Otp{ iOtp: smsOTP, } o.genAndSendOTP(4) fmt.Println("") emailOTP := &Email{} o = Otp{ iOtp: emailOTP, } o.genAndSendOTP(4) } ``` -------------------------------- ### Output of Memento Pattern Swift Example Source: https://refactoring.guru/design-patterns/memento/swift/example This is the execution result of the Swift Memento pattern example. It shows the saved states of the UITextView, including text, color, and selection range, and the state after performing undo operations. ```text Text: First Change Date: hour: 12 minute: 21 second: 50 nanosecond: 821737051 isLeapMonth: false Color: nil Range: {12, 0} Text: Second Change Date: hour: 12 minute: 21 second: 50 nanosecond: 826483011 isLeapMonth: false Color: nil Range: {13, 0} Text: Second Change & Third Change Date: hour: 12 minute: 21 second: 50 nanosecond: 829187035 isLeapMonth: false Color: Optional(UIExtendedSRGBColorSpace 1 0 0 1) Range: {28, 0} Client: Perform Undo operation 2 times Text: First Change Date: hour: 12 minute: 21 second: 50 nanosecond: 821737051 isLeapMonth: false Color: nil Range: {12, 0} ``` -------------------------------- ### Iterator Example Output Source: https://refactoring.guru/design-patterns/iterator/swift/example This output shows the result of executing the conceptual Swift example of the Iterator design pattern. It demonstrates the straight traversal of the `WordsCollection` and the reverse traversal of the `NumbersCollection`. ```text Straight traversal using IteratorProtocol: First Second Third Reverse traversal using AnyIterator: 3 2 1 ``` -------------------------------- ### Client Code Demonstrating Bridge Pattern in Go Source: https://refactoring.guru/design-patterns/bridge/go/example The client code demonstrates the Bridge pattern by instantiating Mac and Windows computers and different printers (HP, Epson). It shows how to set printers for computers and invoke the print functionality, illustrating interchangeability. ```go package main import "fmt" func main() { hpPrinter := &Hp{} epsonPrinter := &Epson{} macComputer := &Mac{} macComputer.SetPrinter(hpPrinter) macComputer.Print() fmt.Println() macComputer.SetPrinter(epsonPrinter) macComputer.Print() fmt.Println() winComputer := &Windows{} winComputer.SetPrinter(hpPrinter) winComputer.Print() fmt.Println() winComputer.SetPrinter(epsonPrinter) winComputer.Print() fmt.Println() } ``` -------------------------------- ### Facade Pattern Conceptual Example Output Source: https://refactoring.guru/design-patterns/facade/csharp/example This is the expected output from the C# conceptual example of the Facade design pattern. It shows the simplified sequence of operations executed by the subsystems through the Facade interface. ```text Facade initializes subsystems: Subsystem1: Ready! Subsystem2: Get ready! Facade orders subsystems to perform the action: Subsystem1: Go! Subsystem2: Fire! ``` -------------------------------- ### Golang Client Code for Facade Pattern Source: https://refactoring.guru/design-patterns/facade/go/example This Go client code demonstrates the usage of the Facade pattern. It initializes a wallet facade and performs operations like adding and deducting money. It hides the complexity of multiple subsystem interactions behind a single facade interface. Dependencies include the fmt and log packages. ```go package main import ( "fmt" "log" ) func main() { fmt.Println() walletFacade := newWalletFacade("abc", 1234) fmt.Println() err := walletFacade.addMoneyToWallet("abc", 1234, 10) if err != nil { log.Fatalf("Error: %s\n", err.Error()) } fmt.Println() err = walletFacade.deductMoneyFromWallet("abc", 1234, 5) if err != nil { log.Fatalf("Error: %s\n", err.Error()) } } ``` -------------------------------- ### Output of C++ Prototype Pattern Example Source: https://refactoring.guru/design-patterns/prototype/cpp/example This text displays the execution result of the C++ Prototype pattern conceptual example. It shows the output generated when creating and using cloned prototype objects. ```text Let's create a Prototype 1 Call Method from PROTOTYPE_1 with field : 90 Let's create a Prototype 2 Call Method from PROTOTYPE_2 with field : 10 ``` -------------------------------- ### Execution Result in Text Source: https://refactoring.guru/design-patterns/command/go/example This file contains the expected output from running the Go client code demonstrating the Command pattern. It shows the sequence of actions performed by the TV receiver. ```text Turning tv on Turning tv off ``` -------------------------------- ### Decorator Pattern Usage Example: Dynamic Configuration Source: https://refactoring.guru/design-patterns/decorator Shows how to dynamically configure data source decorators based on external conditions. This example illustrates building a data source pipeline with compression and encryption decorators conditionally enabled. ```pseudocode // The app can assemble different stacks of decorators at // runtime, depending on the configuration or environment. class ApplicationConfigurator is method configurationExample() is source = new FileDataSource("salary.dat") if (enabledEncryption) source = new EncryptionDecorator(source) if (enabledCompression) source = new CompressionDecorator(source) logger = new SalaryManager(source) salary = logger.load() // ... ``` -------------------------------- ### Visitor Pattern Execution Output in Python Source: https://refactoring.guru/design-patterns/visitor/python/example Shows the output generated by running the conceptual example of the Visitor design pattern in Python. It demonstrates how different concrete visitors interact with concrete components and produce distinct results. ```Text The client code works with all visitors via the base Visitor interface: A + ConcreteVisitor1 B + ConcreteVisitor1 It allows the same client code to work with different types of visitors: A + ConcreteVisitor2 B + ConcreteVisitor2 ``` -------------------------------- ### Decorator Pattern Usage Example: Chaining Decorators Source: https://refactoring.guru/design-patterns/decorator Demonstrates how to assemble multiple decorators to add layered functionality. This example shows creating a data source that is first compressed and then encrypted, illustrating the dynamic nature of the Decorator pattern. ```pseudocode // Option 1. A simple example of a decorator assembly. class Application is method dumbUsageExample() is source = new FileDataSource("somefile.dat") source.writeData(salaryRecords) // The target file has been written with plain data. source = new CompressionDecorator(source) source.writeData(salaryRecords) // The target file has been written with compressed // data. source = new EncryptionDecorator(source) // The source variable now contains this: // Encryption > Compression > FileDataSource source.writeData(salaryRecords) // The file has been written with compressed and // encrypted data. ``` -------------------------------- ### Flyweight Pattern Example in C# Source: https://refactoring.guru/design-patterns/flyweight/csharp/example This C# code demonstrates the Flyweight design pattern. It shows how to create and reuse flyweight objects to reduce memory consumption. The example simulates adding cars to a database, where shared car details are reused. ```csharp using System; using System.Collections; using System.Collections.Generic; namespace Flyweight_Design_Pattern { // The Flyweight interface declares operations with a shared state argument. public interface IFlyweight { void Operation(SharedState outerState); } // The Concrete Flyweight class contains the shared state. public class Flyweight : IFlyweight { private Dictionary _sharedState; public Flyweight(Dictionary sharedState) { this._sharedState = sharedState; } public void Operation(SharedState outerState) { var stringifiedSharedState = string.Join(", ", this._sharedState.Select(x => $"{x.Key}: {x.Value}")); var stringifiedOuterState = string.Join(", ", outerState.GetState().Select(x => $"{x.Key}: {x.Value}")); Console.WriteLine($"Flyweight: Displaying shared {{{stringifiedSharedState}}} and unique {{{stringifiedOuterState}}} state."); } } // The Flyweight Factory manages flyweight objects and their reuse. public class FlyweightFactory { private Dictionary _flyweights = new Dictionary(); public FlyweightFactory(IEnumerable share) { foreach (var flyweight in share) { this._flyweights.Add(this.Getkey(flyweight as Flyweight), flyweight); } } // Generates a unique key from flyweight data. private string Getkey(Flyweight flyweight) { var parts = new List(); // Assuming flyweight has a property that can be used as a key, e.g., Color, Company, Model // This needs to be adapted based on the actual structure of Flyweight. // For demonstration, let's assume a simple key generation. if (flyweight._sharedState.ContainsKey("Company")) parts.Add(flyweight._sharedState["Company"].ToString()); if (flyweight._sharedState.ContainsKey("Model")) parts.Add(flyweight._sharedState["Model"].ToString()); if (flyweight._sharedState.ContainsKey("Color")) parts.Add(flyweight._sharedState["Color"].ToString()); return string.Join("_", parts); } public IFlyweight GetFlyweight(Dictionary sharedState) { var key = FlyweightFactory.Getkey(new Flyweight(sharedState)); if (this._flyweights.ContainsKey(key)) { Console.WriteLine("FlyweightFactory: Reusing existing flyweight."); return this._flyweights[key]; } else { Console.WriteLine("FlyweightFactory: Can't find a flyweight, creating new one."); var newFlyweight = new Flyweight(sharedState); this._flyweights.Add(key, newFlyweight); return newFlyweight; } } public void PrintFlyweights() { var count = _flyweights.Count; Console.WriteLine($"FlyweightFactory: I have {count} flyweights:"); foreach (var pair in _flyweights) { // To print the shared state, we need to access it. This might require a method in Flyweight. // For demonstration, let's assume Flyweight has a property or method to get its shared state. // Example: Console.WriteLine(pair.Value.GetSharedState()); // Since we don't have that, we'll just print the key. Console.WriteLine(pair.Key); } } } // The Context class stores the extrinsic state. It is used for demonstration purposes. public class SharedState { private Dictionary _state = new Dictionary(); public SharedState(Dictionary state) { this._state = state; } public Dictionary GetState() { return this._state; } } // The Client code. It is used for demonstration purposes. public class Client { public void ClientCode(FlyweightFactory flyweightFactory, Car car) { Console.WriteLine("Client: Adding a car to database."); // The client code either stores or calculates extrinsic state and // passes it to the flyweight's methods. var sharedCarState = new Dictionary { ["Color"] = car.Color, ["Model"] = car.Model, ["Company"] = car.Company }; var flyweight = flyweightFactory.GetFlyweight(sharedCarState); flyweight.Operation(new SharedState(new Dictionary { ["Owner"] = car.Owner, ["Number"] = car.Number, ["Company"] = car.Company, ["Model"] = car.Model, ["Color"] = car.Color })); } } public class Car { public string Color { get; set; } public string Model { get; set; } public string Company { get; set; } public string Owner { get; set; } public string Number { get; set; } } public class Program { static void Main(string[] args) { var cars = new List { new Car { Company = "Chevrolet", Model = "Camaro2018", Color = "pink", Owner = "MONICA", Number = "XX0000" }, new Car { Company = "Mercedes Benz", Model = "C300", Color = "black", Owner = "JOHN", Number = "YY1111" }, new Car { Company = "Mercedes Benz", Model = "C500", Color = "red", Owner = "JOHN", Number = "YY1111" }, new Car { Company = "BMW", Model = "M5", Color = "red", Owner = "JAMES DOE", Number = "CL234IR" }, new Car { Company = "BMW", Model = "X6", Color = "white", Owner = "JAMES DOE", Number = "CL234IR" }, new Car { Company = "BMW", Model = "X1", Color = "red", Owner = "JAMES DOE", Number = "CL234IR" } // Added a new car for demonstration }; // Prepare flyweights based on unique combinations of shared properties. var flyweights = cars.Select(car => new Flyweight(new Dictionary { ["Company"] = car.Company, ["Model"] = car.Model, ["Color"] = car.Color })).ToList(); var factory = new FlyweightFactory(flyweights); factory.PrintFlyweights(); var client = new Client(); // Client uses the factory to get flyweights and operates on them. client.ClientCode(factory, cars[0]); // Camaro client.ClientCode(factory, cars[3]); // BMW M5 client.ClientCode(factory, cars[5]); // BMW X1 (new) factory.PrintFlyweights(); } } } ``` -------------------------------- ### Visitor Pattern: C# Conceptual Example Source: https://refactoring.guru/design-patterns/visitor/csharp/example This C# code implements the Visitor design pattern. It includes interfaces for `IComponent` and `IVisitor`, and concrete classes like `ConcreteComponentA`, `ConcreteComponentB`, `ConcreteVisitor1`, and `ConcreteVisitor2`. The `ClientCode` method demonstrates how to apply different visitors to a list of components without altering their classes. ```csharp using System; using System.Collections.Generic; namespace RefactoringGuru.DesignPatterns.Visitor.Conceptual { // The Component interface declares an `accept` method that should take the // base visitor interface as an argument. public interface IComponent { void Accept(IVisitor visitor); } // Each Concrete Component must implement the `Accept` method in such a way // that it calls the visitor's method corresponding to the component's // class. public class ConcreteComponentA : IComponent { // Note that we're calling `VisitConcreteComponentA`, which matches the // current class name. This way we let the visitor know the class of the // component it works with. public void Accept(IVisitor visitor) { visitor.VisitConcreteComponentA(this); } // Concrete Components may have special methods that don't exist in // their base class or interface. The Visitor is still able to use these // methods since it's aware of the component's concrete class. public string ExclusiveMethodOfConcreteComponentA() { return "A"; } } public class ConcreteComponentB : IComponent { // Same here: VisitConcreteComponentB => ConcreteComponentB public void Accept(IVisitor visitor) { visitor.VisitConcreteComponentB(this); } public string SpecialMethodOfConcreteComponentB() { return "B"; } } // The Visitor Interface declares a set of visiting methods that correspond // to component classes. The signature of a visiting method allows the // visitor to identify the exact class of the component that it's dealing // with. public interface IVisitor { void VisitConcreteComponentA(ConcreteComponentA element); void VisitConcreteComponentB(ConcreteComponentB element); } // Concrete Visitors implement several versions of the same algorithm, which // can work with all concrete component classes. // // You can experience the biggest benefit of the Visitor pattern when using // it with a complex object structure, such as a Composite tree. In this // case, it might be helpful to store some intermediate state of the // algorithm while executing visitor's methods over various objects of the // structure. class ConcreteVisitor1 : IVisitor { public void VisitConcreteComponentA(ConcreteComponentA element) { Console.WriteLine(element.ExclusiveMethodOfConcreteComponentA() + " + ConcreteVisitor1"); } public void VisitConcreteComponentB(ConcreteComponentB element) { Console.WriteLine(element.SpecialMethodOfConcreteComponentB() + " + ConcreteVisitor1"); } } class ConcreteVisitor2 : IVisitor { public void VisitConcreteComponentA(ConcreteComponentA element) { Console.WriteLine(element.ExclusiveMethodOfConcreteComponentA() + " + ConcreteVisitor2"); } public void VisitConcreteComponentB(ConcreteComponentB element) { Console.WriteLine(element.SpecialMethodOfConcreteComponentB() + " + ConcreteVisitor2"); } } public class Client { // The client code can run visitor operations over any set of elements // without figuring out their concrete classes. The accept operation // directs a call to the appropriate operation in the visitor object. public static void ClientCode(List components, IVisitor visitor) { foreach (var component in components) { component.Accept(visitor); } } } class Program { static void Main(string[] args) { List components = new List { new ConcreteComponentA(), new ConcreteComponentB() }; Console.WriteLine("The client code works with all visitors via the base Visitor interface:"); var visitor1 = new ConcreteVisitor1(); Client.ClientCode(components,visitor1); Console.WriteLine(); Console.WriteLine("It allows the same client code to work with different types of visitors:"); var visitor2 = new ConcreteVisitor2(); Client.ClientCode(components, visitor2); } } } ``` -------------------------------- ### Factory Method Real-World Example in Swift Source: https://refactoring.guru/design-patterns/factory-method/swift/example A practical implementation of the Factory Method pattern in Swift, demonstrating how to create projectors (e.g., WifiProjector, BluetoothProjector) using factories. This example showcases deferred instantiation and how the client code interacts with projectors through a common interface. ```swift import XCTest class FactoryMethodRealWorld: XCTestCase { func testFactoryMethodRealWorld() { let info = "Very important info of the presentation" let clientCode = ClientCode() /// Present info over WiFi clientCode.present(info: info, with: WifiFactory()) /// Present info over Bluetooth clientCode.present(info: info, with: BluetoothFactory()) } } protocol ProjectorFactory { func createProjector() -> Projector func syncedProjector(with projector: Projector) -> Projector } extension ProjectorFactory { /// Base implementation of ProjectorFactory func syncedProjector(with projector: Projector) -> Projector { /// Every instance creates an own projector let newProjector = createProjector() /// sync projectors newProjector.sync(with: projector) return newProjector } } class WifiFactory: ProjectorFactory { func createProjector() -> Projector { return WifiProjector() } } class BluetoothFactory: ProjectorFactory { func createProjector() -> Projector { return BluetoothProjector() } } protocol Projector { /// Abstract projector interface var currentPage: Int { get } func present(info: String) func sync(with projector: Projector) func update(with page: Int) } extension Projector { /// Base implementation of Projector methods func sync(with projector: Projector) { projector.update(with: currentPage) } } class WifiProjector: Projector { var currentPage = 0 func present(info: String) { print("Info is presented over Wifi: \(info)") } func update(with page: Int) { /// ... scroll page via WiFi connection /// ... currentPage = page } } class BluetoothProjector: Projector { var currentPage = 0 func present(info: String) { print("Info is presented over Bluetooth: \(info)") } func update(with page: Int) { /// ... scroll page via Bluetooth connection /// ... currentPage = page } } private class ClientCode { private var currentProjector: Projector? func present(info: String, with factory: ProjectorFactory) { /// Check whether the client code is already presenting something... guard let projector = currentProjector else { /// 'currentProjector' variable is nil. Create a new projector and /// start presentation. let projector = factory.createProjector() projector.present(info: info) self.currentProjector = projector return } /// Client code already has a projector. Let's sync pages of the old /// projector with a new one. self.currentProjector = factory.syncedProjector(with: projector) self.currentProjector?.present(info: info) } } ``` -------------------------------- ### Mediator Pattern Conceptual Example Output in Text Source: https://refactoring.guru/design-patterns/mediator/cpp/example This is the execution result of the C++ Mediator pattern conceptual example. It shows the sequence of operations triggered by the client and how the mediator coordinates actions between `Component1` and `Component2`. ```text Client triggers operation A. Component 1 does A. Mediator reacts on A and triggers following operations: Component 2 does C. Client triggers operation D. Component 2 does D. Mediator reacts on D and triggers following operations: Component 1 does B. Component 2 does C. ``` -------------------------------- ### Flyweight Pattern Conceptual Example in TypeScript Source: https://refactoring.guru/design-patterns/flyweight/typescript/example Illustrates the Flyweight pattern's structure and roles of its classes. It demonstrates how intrinsic state is shared and extrinsic state is passed to operations. This example requires no external dependencies. ```typescript /** * The Flyweight stores a common portion of the state (also called intrinsic * state) that belongs to multiple real business entities. The Flyweight accepts * the rest of the state (extrinsic state, unique for each entity) via its * method parameters. */ class Flyweight { private sharedState: any; constructor(sharedState: any) { this.sharedState = sharedState; } public operation(uniqueState): void { const s = JSON.stringify(this.sharedState); const u = JSON.stringify(uniqueState); console.log(`Flyweight: Displaying shared (${s}) and unique (${u}) state.`); } } /** * The Flyweight Factory creates and manages the Flyweight objects. It ensures * that flyweights are shared correctly. When the client requests a flyweight, * the factory either returns an existing instance or creates a new one, if it * doesn't exist yet. */ class FlyweightFactory { private flyweights: {[key: string]: Flyweight} = {}; constructor(initialFlyweights: string[][]) { for (const state of initialFlyweights) { this.flyweights[this.getKey(state)] = new Flyweight(state); } } /** * Returns a Flyweight's string hash for a given state. */ private getKey(state: string[]): string { return state.join('_'); } /** * Returns an existing Flyweight with a given state or creates a new one. */ public getFlyweight(sharedState: string[]): Flyweight { const key = this.getKey(sharedState); if (!(key in this.flyweights)) { console.log('FlyweightFactory: Can't find a flyweight, creating new one.'); this.flyweights[key] = new Flyweight(sharedState); } else { console.log('FlyweightFactory: Reusing existing flyweight.'); } return this.flyweights[key]; } public listFlyweights(): void { const count = Object.keys(this.flyweights).length; console.log(`\nFlyweightFactory: I have ${count} flyweights:`) for (const key in this.flyweights) { console.log(key); } } } /** * The client code usually creates a bunch of pre-populated flyweights in the * initialization stage of the application. */ const factory = new FlyweightFactory([ ['Chevrolet', 'Camaro2018', 'pink'], ['Mercedes Benz', 'C300', 'black'], ['Mercedes Benz', 'C500', 'red'], ['BMW', 'M5', 'red'], ['BMW', 'X6', 'white'], // ... ]); factory.listFlyweights(); // ... function addCarToPoliceDatabase( ff: FlyweightFactory, plates: string, owner: string, brand: string, model: string, color: string, ) { console.log('\nClient: Adding a car to database.'); const flyweight = ff.getFlyweight([brand, model, color]); // The client code either stores or calculates extrinsic state and passes it // to the flyweight's methods. flyweight.operation([plates, owner]); } addCarToPoliceDatabase(factory, 'CL234IR', 'James Doe', 'BMW', 'M5', 'red'); addCarToPoliceDatabase(factory, 'CL234IR', 'James Doe', 'BMW', 'X1', 'red'); factory.listFlyweights(); ``` -------------------------------- ### Demo Initialization and Testing (Java) Source: https://refactoring.guru/design-patterns/proxy/java/example This Java code demonstrates the usage of the `YouTubeDownloader` with both a direct `ThirdPartyYouTubeClass` and a `YouTubeCacheProxy`. It includes a `test` method to measure the time taken for rendering videos and popular lists, highlighting the performance benefits of the caching proxy. ```java package refactoring_guru.proxy.example; import refactoring_guru.proxy.example.downloader.YouTubeDownloader; import refactoring_guru.proxy.example.proxy.YouTubeCacheProxy; import refactoring_guru.proxy.example.some_cool_media_library.ThirdPartyYouTubeClass; public class Demo { public static void main(String[] args) { YouTubeDownloader naiveDownloader = new YouTubeDownloader(new ThirdPartyYouTubeClass()); YouTubeDownloader smartDownloader = new YouTubeDownloader(new YouTubeCacheProxy()); long naive = test(naiveDownloader); long smart = test(smartDownloader); System.out.print("Time saved by caching proxy: " + (naive - smart) + "ms"); } private static long test(YouTubeDownloader downloader) { long startTime = System.currentTimeMillis(); // User behavior in our app: downloader.renderPopularVideos(); downloader.renderVideoPage("catzzzzzzzzz"); downloader.renderPopularVideos(); downloader.renderVideoPage("dancesvideoo"); // Users might visit the same page quite often. downloader.renderVideoPage("catzzzzzzzzz"); downloader.renderVideoPage("someothervid"); long estimatedTime = System.currentTimeMillis() - startTime; System.out.print("Time elapsed: " + estimatedTime + "ms\n"); return estimatedTime; } } ``` -------------------------------- ### Client Code for Composite Pattern in Go Source: https://refactoring.guru/design-patterns/composite/go/example Demonstrates the client code that utilizes the Composite pattern. It shows how to create a tree structure of components (folders and files) and interact with them uniformly through the Component interface, such as performing a search operation. ```go package main func main() { file1 := &File{name: "File1"} file2 := &File{name: "File2"} file3 := &File{name: "File3"} folder1 := &Folder{ name: "Folder1", } folder1.add(file1) folder2 := &Folder{ name: "Folder2", } folder2.add(file2) folder2.add(file3) folder2.add(folder1) folder2.search("rose") } ```