### Conceptual Example Output in Swift Source: https://refactoring.guru/design-patterns/command/swift/example Shows the expected output when the conceptual Command pattern example is executed. This helps in verifying the behavior of the implemented commands. ```text Invoker: Does anybody want something done before I begin? SimpleCommand: See, I can do simple things like printing (Say Hi!) Invoker: ...doing something really important... Invoker: Does anybody want something done after I finish? ComplexCommand: Complex stuff should be done by a receiver object. Receiver: Working on (Send email) Receiver: Also working on (Save report) ``` -------------------------------- ### Conceptual Example Output Source: https://refactoring.guru/design-patterns/adapter/swift/example Shows the execution result of the conceptual Adapter pattern example, demonstrating the client's interaction with the Target and the adapted Adaptee. ```text Client: I can work just fine with the Target objects: Target: The default target's behavior. Client: The Adaptee class has a weird interface. See, I don't understand it: Adaptee: .eetpadA eht fo roivaheb laicepS Client: But I can work with it via the Adapter: Adapter: (TRANSLATED) Special behavior of the Adaptee. ``` -------------------------------- ### Factory Method Pattern: Real-World Example Output Source: https://refactoring.guru/design-patterns/factory-method/swift/example This output shows the result of running the real-world Swift example, demonstrating how information is presented via both WiFi and Bluetooth projectors. ```text Info is presented over Wifi: Very important info of the presentation Info is presented over Bluetooth: Very important info of the presentation ``` -------------------------------- ### Execution Result of Adapter Pattern Example Source: https://refactoring.guru/design-patterns/adapter/cpp/example Shows the output generated by running the conceptual example of the Adapter pattern. It demonstrates the client's interaction with both the Target and the Adaptee through the Adapter. ```txt Client: I can work just fine with the Target objects: Target: The default target's behavior. Client: The Adaptee class has a weird interface. See, I don't understand it: Adaptee: .eetpadA eht fo roivaheb laicepS Client: But I can work with it via the Adapter: Adapter: (TRANSLATED) Special behavior of the Adaptee. ``` -------------------------------- ### Conceptual Example Output in PHP Source: https://refactoring.guru/design-patterns/state/php/example Shows the execution result of the conceptual State pattern example. Observe how the context transitions between states and how each state handles requests. ```text Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateA. ConcreteStateA handles request1. ConcreteStateA wants to change the state of the context. Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateB. ConcreteStateB handles request2. ConcreteStateB wants to change the state of the context. Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateA. ``` -------------------------------- ### Program.cs: Conceptual Example Source: https://refactoring.guru/design-patterns/builder/csharp/example Demonstrates the conceptual usage of the Builder pattern without a Director class. This example shows how to manually invoke builder methods to construct a product and retrieve its parts. ```csharp // Remember, the Builder pattern can be used without a Director // class. Console.WriteLine("Custom product:"); builder.BuildPartA(); builder.BuildPartC(); Console.Write(builder.GetProduct().ListParts()); } } } ``` -------------------------------- ### Execution Result of Conceptual Adapter Example Source: https://refactoring.guru/design-patterns/adapter/csharp/example This output shows the result of running the conceptual Adapter pattern example, illustrating the interaction between the client, adapter, and adaptee. ```text Adaptee interface is incompatible with the client. But with adapter client can call it's method. This is 'Specific request.' ``` -------------------------------- ### Conceptual Example Output in Swift Source: https://refactoring.guru/design-patterns/decorator/swift/example Shows the execution result of the conceptual Decorator pattern example, demonstrating the output from a simple component and a component wrapped by multiple decorators. ```text Client: I've got a simple component Result: ConcreteComponent Client: Now I've got a decorated component Result: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent)) ``` -------------------------------- ### Client Code Setup Source: https://refactoring.guru/design-patterns/mediator/php/example Initializes the UserRepository, Logger, and OnboardingNotification components and attaches them to specific events using the event system. ```php $repository = new UserRepository(); events()->attach($repository, "facebook:update"); $logger = new Logger(__DIR__ . "/log.txt"); events()->attach($logger, "*"); $onboarding = new OnboardingNotification("1@example.com"); events()->attach($onboarding, "users:created"); // ... $repository->initialize(__DIR__ . " users.csv"); // ... $user = $repository->createUser([ "name" => "John Smith", "email" => "john99@example.com", ]); // ... $user->delete(); ``` -------------------------------- ### Naive Singleton Implementation in C++ Source: https://refactoring.guru/design-patterns/singleton/cpp/example This example demonstrates a basic Singleton implementation in C++. It is not thread-safe and can lead to multiple instances in a multithreaded environment. Use this as a conceptual starting point. ```cpp /** * The Singleton class defines the `GetInstance` method that serves as an * alternative to constructor and lets clients access the same instance of this * class over and over. */ class Singleton { /** * The Singleton's constructor should always be private to prevent direct * construction calls with the `new` operator. */ protected: Singleton(const std::string value): value_(value) { } static Singleton* singleton_; std::string value_; public: /** * Singletons should not be cloneable. */ Singleton(Singleton &other) = delete; /** * Singletons should not be assignable. */ void operator=(const Singleton &) = delete; /** * This is the static method that controls the access to the singleton * instance. On the first run, it creates a singleton object and places it * into the static field. On subsequent runs, it returns the client existing * object stored in the static field. */ static Singleton *GetInstance(const std::string& value); /** * Finally, any singleton should define some business logic, which can be * executed on its instance. */ void SomeBusinessLogic() { // ... } std::string value() const{ return value_; } }; Singleton* Singleton::singleton_= nullptr;; /** * Static methods should be defined outside the class. */ Singleton *Singleton::GetInstance(const std::string& value) { /** * This is a safer way to create an instance. instance = new Singleton is * dangeruous in case two instance threads wants to access at the same time */ if(singleton_==nullptr){ singleton_ = new Singleton(value); } return singleton_; } void ThreadFoo(){ // Following code emulates slow initialization. std::this_thread::sleep_for(std::chrono::milliseconds(1000)); Singleton* singleton = Singleton::GetInstance("FOO"); std::cout << singleton->value() << "\n"; } void ThreadBar(){ // Following code emulates slow initialization. std::this_thread::sleep_for(std::chrono::milliseconds(1000)); Singleton* singleton = Singleton::GetInstance("BAR"); std::cout << singleton->value() << "\n"; } int main() { std::cout <<"If you see the same value, then singleton was reused (yay!\n" << "If you see different values, then 2 singletons were created (booo!!)\n\n" << "RESULT:\n"; std::thread t1(ThreadFoo); std::thread t2(ThreadBar); t1.join(); t2.join(); return 0; } ``` -------------------------------- ### Prototype Registry/Factory in Java Source: https://refactoring.guru/design-patterns/prototype/java/example This example implements a prototype factory using a HashMap to cache and retrieve cloned objects. The factory initializes with predefined shapes and provides a get() method to return clones of cached prototypes. ```java package refactoring_guru.prototype.caching.cache; import refactoring_guru.prototype.example.shapes.Circle; import refactoring_guru.prototype.example.shapes.Rectangle; import refactoring_guru.prototype.example.shapes.Shape; import java.util.HashMap; import java.util.Map; public class BundledShapeCache { private Map cache = new HashMap<>(); public BundledShapeCache() { Circle circle = new Circle(); circle.x = 5; circle.y = 7; circle.radius = 45; circle.color = "Green"; Rectangle rectangle = new Rectangle(); rectangle.x = 6; rectangle.y = 9; rectangle.width = 8; rectangle.height = 10; rectangle.color = "Blue"; cache.put("Big green circle", circle); cache.put("Medium blue rectangle", rectangle); } public Shape put(String key, Shape shape) { cache.put(key, shape); return shape; } public Shape get(String key) { return cache.get(key).clone(); } } ``` -------------------------------- ### Demo Class - Initialization and Setup in Java Source: https://refactoring.guru/design-patterns/state/java/example The Demo class serves as the entry point for the application, initializing the Player and UI components. ```Java package refactoring_guru.state.example; import refactoring_guru.state.example.ui.Player; import refactoring_guru.state.example.ui.UI; /** * Demo class. Everything comes together here. */ public class Demo { public static void main(String[] args) { Player player = new Player(); UI ui = new UI(player); ui.init(); } } ``` -------------------------------- ### Client Code Example in C# Source: https://refactoring.guru/design-patterns/builder/csharp/example Demonstrates how to use the Director and Concrete Builder to construct different product configurations. The final product is retrieved from the builder. ```csharp class Program { static void Main(string[] args) { var director = new Director(); var builder = new ConcreteBuilder(); director.Builder = builder; Console.WriteLine("Standard basic product:"); director.BuildMinimalViableProduct(); Console.WriteLine(builder.GetProduct().ListParts()); Console.WriteLine("Standard full featured product:"); director.BuildFullFeaturedProduct(); Console.WriteLine(builder.GetProduct().ListParts()); ``` -------------------------------- ### Naïve Singleton Implementation in C# Source: https://refactoring.guru/design-patterns/singleton/csharp/example This example demonstrates a basic, non-thread-safe implementation of the Singleton pattern. It hides the constructor and provides a static method to get the single instance. Be aware that this version can lead to issues in multithreaded environments. ```csharp using System; namespace RefactoringGuru.DesignPatterns.Singleton.Conceptual.NonThreadSafe { // The Singleton class defines the `GetInstance` method that serves as an // alternative to constructor and lets clients access the same instance of // this class over and over. // EN : The Singleton should always be a 'sealed' class to prevent class // inheritance through external classes and also through nested classes. public sealed class Singleton { // The Singleton's constructor should always be private to prevent // direct construction calls with the `new` operator. private Singleton() { } // The Singleton's instance is stored in a static field. There there are // multiple ways to initialize this field, all of them have various pros // and cons. In this example we'll show the simplest of these ways, // which, however, doesn't work really well in multithreaded program. private static Singleton _instance; // This is the static method that controls the access to the singleton // instance. On the first run, it creates a singleton object and places // it into the static field. On subsequent runs, it returns the client // existing object stored in the static field. public static Singleton GetInstance() { if (_instance == null) { _instance = new Singleton(); } return _instance; } // Finally, any singleton should define some business logic, which can // be executed on its instance. public void someBusinessLogic() { // ... } } class Program { static void Main(string[] args) { // The client code. Singleton s1 = Singleton.GetInstance(); Singleton s2 = Singleton.GetInstance(); if (s1 == s2) { Console.WriteLine("Singleton works, both variables contain the same instance."); } else { Console.WriteLine("Singleton failed, variables contain different instances."); } } } } ``` ```text Singleton works, both variables contain the same instance. ``` -------------------------------- ### Client Code and Setup (PHP) Source: https://refactoring.guru/design-patterns/visitor/php/example Sets up the company structure with departments and employees, then initializes the locale for monetary formatting before the visitor can be applied. ```php /** * The client code. */ $mobileDev = new Department("Mobile Development", [ new Employee("Albert Falmore", "designer", 100000), new Employee("Ali Halabay", "programmer", 100000), new Employee("Sarah Konor", "programmer", 90000), new Employee("Monica Ronaldino", "QA engineer", 31000), new Employee("James Smith", "QA engineer", 30000), ]); $techSupport = new Department("Tech Support", [ new Employee("Larry Ulbrecht", "supervisor", 70000), new Employee("Elton Pale", "operator", 30000), new Employee("Rajeet Kumar", "operator", 30000), new Employee("John Burnovsky", "operator", 34000), new Employee("Sergey Korolev", "operator", 35000), ]); $company = new Company("SuperStarDevelopment", [$mobileDev, $techSupport]); setlocale(LC_MONETARY, 'en_US'); ``` -------------------------------- ### Chain of Responsibility Execution Result in C++ Source: https://refactoring.guru/design-patterns/chain-of-responsibility/cpp/example This output shows the result of executing the Chain of Responsibility example in C++. It demonstrates how requests for 'Nut' and 'Banana' are handled by the respective handlers in the chain, while 'Cup of coffee' is left untouched. It also shows the behavior when starting the chain from a different handler. ```txt Chain: Monkey > Squirrel > Dog Client: Who wants a Nut? Squirrel: I'll eat the Nut. Client: Who wants a Banana? Monkey: I'll eat the Banana. Client: Who wants a Cup of coffee? Cup of coffee was left untouched. Subchain: Squirrel > Dog Client: Who wants a Nut? Squirrel: I'll eat the Nut. Client: Who wants a Banana? Banana was left untouched. Client: Who wants a Cup of coffee? Cup of coffee was left untouched. ``` -------------------------------- ### Application Configuration and Factory Selection Source: https://refactoring.guru/design-patterns/abstract-factory Demonstrates how the application selects and instantiates the appropriate concrete factory at runtime based on the operating system configuration. ```pseudocode class ApplicationConfigurator is method main() is config = readApplicationConfigFile() if (config.OS == "Windows") then factory = new WinFactory() else if (config.OS == "Mac") then factory = new MacFactory() else throw new Exception("Error! Unknown operating system.") Application app = new Application(factory) ``` -------------------------------- ### Prototype Conceptual Example Output Source: https://refactoring.guru/design-patterns/prototype/swift/example The execution result of the conceptual Prototype example, showing the cloning process and object equality. ```text Values defined in BaseClass have been cloned! Values defined in SubClass have been cloned! The original object is equal to the copied object! ``` -------------------------------- ### Client Code Example in C++ Source: https://refactoring.guru/design-patterns/builder/cpp/example Demonstrates how client code uses the Director and ConcreteBuilder to construct a product. It initiates the building process and retrieves the result. ```cpp void ClientCode(Director& director) { ConcreteBuilder1* builder = new ConcreteBuilder1(); director.set_builder(builder); std::cout << "Standard basic product:\n"; director.BuildMinimalViableProduct(); ``` -------------------------------- ### Flyweight Example Execution Result Source: https://refactoring.guru/design-patterns/flyweight/ruby/example Shows the output of the conceptual Flyweight example, demonstrating the creation and reuse of flyweight objects. ```text FlyweightFactory: I have 5 flyweights: Camaro2018_Chevrolet_pink C300_Mercedes Benz_black C500_Mercedes Benz_red BMW_M5_red BMW_X6_white Client: Adding a car to database. FlyweightFactory: Reusing existing flyweight. Flyweight: Displaying shared (["BMW","M5","red"]) and unique (["CL234IR","James Doe"]) state. Client: Adding a car to database. FlyweightFactory: Can't find a flyweight, creating new one. Flyweight: Displaying shared (["BMW","X1","red"]) and unique (["CL234IR","James Doe"]) state. FlyweightFactory: I have 6 flyweights: Camaro2018_Chevrolet_pink C300_Mercedes Benz_black C500_Mercedes Benz_red BMW_M5_red BMW_X6_white BMW_X1_red ``` -------------------------------- ### Demo Initialization in Java Source: https://refactoring.guru/design-patterns/mediator/java/example Sets up the Mediator and registers various UI components for the editor. This code demonstrates the main entry point for the Mediator pattern example. ```java package refactoring_guru.mediator.example; import refactoring_guru.mediator.example.components.*; import refactoring_guru.mediator.example.mediator.Editor; import refactoring_guru.mediator.example.mediator.Mediator; import javax.swing.*; /** * Demo class. Everything comes together here. */ public class Demo { public static void main(String[] args) { Mediator mediator = new Editor(); mediator.registerComponent(new Title()); mediator.registerComponent(new TextBox()); mediator.registerComponent(new AddButton()); mediator.registerComponent(new DeleteButton()); mediator.registerComponent(new SaveButton()); mediator.registerComponent(new List(new DefaultListModel())); mediator.registerComponent(new Filter()); mediator.createGUI(); } } ``` -------------------------------- ### Client Code: Assembling and Pricing Pizza (Go) Source: https://refactoring.guru/design-patterns/decorator/go/example Demonstrates how to use the decorators to dynamically add toppings to a pizza and calculate the final price. Requires the fmt package for output. ```go package main import "fmt" func main() { pizza := &VeggieMania{} //Add cheese topping pizzaWithCheese := &CheeseTopping{ pizza: pizza, } //Add tomato topping pizzaWithCheeseAndTomato := &TomatoTopping{ pizza: pizzaWithCheese, } fmt.Printf("Price of veggeMania with tomato and cheese topping is %d\n", pizzaWithCheeseAndTomato.getPrice()) } ``` -------------------------------- ### Execution Result of Decorator Pattern Example Source: https://refactoring.guru/design-patterns/decorator/ruby/example Shows the output generated by the conceptual example, demonstrating the behavior of a simple component and a component wrapped by multiple decorators. ```text Client: I've got a simple component: RESULT: ConcreteComponent Client: Now I've got a decorated component: RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent)) ``` -------------------------------- ### Demo Application Configuration (Java) Source: https://refactoring.guru/design-patterns/abstract-factory/java/example Configures the application by selecting a concrete GUI factory based on the operating system at runtime. This demonstrates how the client can be decoupled from concrete factory implementations. ```java package refactoring_guru.abstract_factory.example; import refactoring_guru.abstract_factory.example.app.Application; import refactoring_guru.abstract_factory.example.factories.GUIFactory; import refactoring_guru.abstract_factory.example.factories.MacOSFactory; import refactoring_guru.abstract_factory.example.factories.WindowsFactory; /** * Demo class. Everything comes together here. */ public class Demo { /** * Application picks the factory type and creates it in run time (usually at * initialization stage), depending on the configuration or environment * variables. */ private static Application configureApplication() { Application app; GUIFactory factory; String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("mac")) { factory = new MacOSFactory(); } else { factory = new WindowsFactory(); } app = new Application(factory); return app; } public static void main(String[] args) { Application app = configureApplication(); app.paint(); } } ``` -------------------------------- ### Application Initialization with Proxy Source: https://refactoring.guru/design-patterns/proxy Demonstrates how the application can initialize and use the proxy object transparently. The manager class receives the proxy instead of the real service. ```pseudocode class Application is method init() is aYouTubeService = new ThirdPartyYouTubeClass() aYouTubeProxy = new CachedYouTubeClass(aYouTubeService) manager = new YouTubeManager(aYouTubeProxy) manager.reactOnUserInput() ``` -------------------------------- ### Execution Result of Conceptual Example in Ruby Source: https://refactoring.guru/design-patterns/command/ruby/example Shows the output generated by running the conceptual example code. This helps in verifying the behavior of the Command pattern implementation. ```text Invoker: Does anybody want something done before I begin? SimpleCommand: See, I can do simple things like printing (Say Hi!) Invoker: ...doing something really important... Invoker: Does anybody want something done after I finish? ComplexCommand: Complex stuff should be done by a receiver object Receiver: Working on (Send email.) Receiver: Also working on (Save report.) ``` -------------------------------- ### Execution Result of Chain of Responsibility Example Source: https://refactoring.guru/design-patterns/chain-of-responsibility/python/example Shows the output generated by the conceptual example, demonstrating how requests are handled by different objects in the chain or left untouched. ```text Chain: Monkey > Squirrel > Dog Client: Who wants a Nut? Squirrel: I'll eat the Nut Client: Who wants a Banana? Monkey: I'll eat the Banana Client: Who wants a Cup of coffee? Cup of coffee was left untouched. Subchain: Squirrel > Dog Client: Who wants a Nut? Squirrel: I'll eat the Nut Client: Who wants a Banana? Banana was left untouched. Client: Who wants a Cup of coffee? Cup of coffee was left untouched. ``` -------------------------------- ### Music Player Application Setup in Rust Source: https://refactoring.guru/design-patterns/state/rust/example Sets up the main application structure, including the `Player` and initial `State`. It configures the Cursive UI with buttons for player controls and global keybindings. ```rust mod player; mod state; use cursive::{ event::Key, view::Nameable, views::{Dialog, TextView}, Cursive, }; use player::Player; use state::{State, StoppedState}; // Application context: a music player and a state. struct PlayerApplication { player: Player, state: Box, } fn main() { let mut app = cursive::default(); app.set_user_data(PlayerApplication { player: Player::default(), state: Box::new(StoppedState), }); app.add_layer( Dialog::around(TextView::new("Press Play").with_name("Player Status")) .title("Music Player") .button("Play", |s| execute(s, "Play")) .button("Stop", |s| execute(s, "Stop")) .button("Prev", |s| execute(s, "Prev")) .button("Next", |s| execute(s, "Next")), ); app.add_global_callback(Key::Esc, |s| s.quit()); app.run(); } fn execute(s: &mut Cursive, button: &'static str) { let PlayerApplication { mut player, mut state, } = s.take_user_data().unwrap(); let mut view = s.find_name::("Player Status").unwrap(); // Here is how state mechanics work: the previous state // executes an action and returns a new state. // Each state has all 4 operations but reacts differently. state = match button { "Play" => state.play(&mut player), "Stop" => state.stop(&mut player), "Prev" => state.prev(&mut player), "Next" => state.next(&mut player), _ => unreachable!(), }; state.render(&player, &mut view); s.set_user_data(PlayerApplication { player, state }); } ``` -------------------------------- ### Execution Result of Bridge Pattern Example Source: https://refactoring.guru/design-patterns/bridge/python/example Shows the output generated by running the conceptual example code, demonstrating how different implementations produce distinct results. ```text Abstraction: Base operation with: ConcreteImplementationA: Here's the result on the platform A. ExtendedAbstraction: Extended operation with: ConcreteImplementationB: Here's the result on the platform B. ``` -------------------------------- ### Main Execution (main.go) Source: https://refactoring.guru/design-patterns/adapter/go/example The main function demonstrating the usage of the client with both a compatible Mac and an incompatible Windows machine via the adapter. ```go package main func main() { client := &Client{} mac := &Mac{} client.InsertLightningConnectorIntoComputer(mac) windowsMachine := &Windows{} windowsMachineAdapter := &WindowsAdapter{ windowMachine: windowsMachine, } client.InsertLightningConnectorIntoComputer(windowsMachineAdapter) } ``` -------------------------------- ### Execution Result of Conceptual Strategy Example Source: https://refactoring.guru/design-patterns/strategy/swift/example Shows the output generated by running the conceptual Strategy pattern example, demonstrating the interchangeable behavior of different sorting algorithms. ```text Client: Strategy is set to normal sorting. Context: Sorting data using the strategy (not sure how it'll do it) a,b,c,d,e Client: Strategy is set to reverse sorting. Context: Sorting data using the strategy (not sure how it'll do it) e,d,c,b,a ``` -------------------------------- ### Execution Result of State Pattern Example Source: https://refactoring.guru/design-patterns/state/cpp/example This output shows the execution flow of the State pattern example, detailing the context transitions between ConcreteStateA and ConcreteStateB as requests are handled. ```text Context: Transition to 14ConcreteStateA. ConcreteStateA handles request1. ConcreteStateA wants to change the state of the context. Context: Transition to 14ConcreteStateB. ConcreteStateB handles request2. ConcreteStateB wants to change the state of the context. Context: Transition to 14ConcreteStateA. ``` -------------------------------- ### Client Code Example Source: https://refactoring.guru/design-patterns/bridge Demonstrates how the client code links an abstraction (RemoteControl) with a specific implementation (Tv or Radio) and uses them. ```pseudocode tv = new Tv() remote = new RemoteControl(tv) remote.togglePower() radio = new Radio() remote = new AdvancedRemoteControl(radio) ``` -------------------------------- ### Conceptual Iterator Example Output in PHP Source: https://refactoring.guru/design-patterns/iterator/php/example Shows the expected output when running the conceptual Iterator example. This helps verify the traversal logic for both forward and reverse iteration. ```text Straight traversal: First Second Third Reverse traversal: Third Second First ``` -------------------------------- ### Client Code for Prototype Pattern in Go Source: https://refactoring.guru/design-patterns/prototype/go/example Demonstrates creating a file system hierarchy and cloning it using the prototype objects. ```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(" ") } ``` -------------------------------- ### Conceptual Facade Example Output in Swift Source: https://refactoring.guru/design-patterns/facade/swift/example The execution result of the conceptual Facade pattern example, demonstrating the simplified output provided by the Facade class after interacting with its subsystems. ```text Facade initializes subsystems: Sybsystem1: Ready! Sybsystem2: Get ready! Facade orders subsystems to perform the action: Sybsystem1: Go! Sybsystem2: Fire! ``` -------------------------------- ### Main Client Code in Go Source: https://refactoring.guru/design-patterns/command/go/example The client code sets up the TV, creates OnCommand and OffCommand objects, and associates them with Button invokers. It then triggers the commands. ```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() } ``` -------------------------------- ### Execution Result of Facade Example Source: https://refactoring.guru/design-patterns/facade/ruby/example This output shows the result of running the conceptual Facade example. It illustrates how the Facade orchestrates calls to its subsystems and presents a consolidated output. ```text Facade initializes subsystems: Subsystem1: Ready! Subsystem2: Get ready! Facade orders subsystems to perform the action: Subsystem1: Go! Subsystem2: Fire! ``` -------------------------------- ### Real-world Observer Pattern Example in PHP Source: https://refactoring.guru/design-patterns/observer/php/example This snippet demonstrates attaching observers (Logger, OnboardingNotification) to a repository and then performing operations (initialize, createUser, deleteUser) that would trigger notifications to the attached observers. It shows how different observers can react to repository events. ```php $repository->attach(new Logger(__DIR__ . "/log.txt"), "*"); $repository->attach(new OnboardingNotification("1@example.com"), "users:created"); $repository->initialize(__DIR__ . "/users.csv"); // ... $user = $repository->createUser([ "name" => "John Smith", "email" => "john99@example.com", ]); // ... $repository->deleteUser($user); ``` -------------------------------- ### Swift Visitor Pattern: Notification Example Source: https://refactoring.guru/design-patterns/visitor/swift/example Defines the core protocols and structures for the Visitor pattern, including `Notification` elements and `NotificationPolicy` visitors. This forms the basis for the real-world example. ```swift import Foundation import XCTest protocol Notification: CustomStringConvertible { func accept(visitor: NotificationPolicy) -> Bool } struct Email { let emailOfSender: String var description: String { return "Email" } } struct SMS { let phoneNumberOfSender: String var description: String { return "SMS" } } struct Push { let usernameOfSender: String var description: String { return "Push" } } extension Email: Notification { func accept(visitor: NotificationPolicy) -> Bool { return visitor.isTurnedOn(for: self) } } extension SMS: Notification { func accept(visitor: NotificationPolicy) -> Bool { return visitor.isTurnedOn(for: self) } } extension Push: Notification { func accept(visitor: NotificationPolicy) -> Bool { return visitor.isTurnedOn(for: self) } } protocol NotificationPolicy: CustomStringConvertible { func isTurnedOn(for email: Email) -> Bool func isTurnedOn(for sms: SMS) -> Bool func isTurnedOn(for push: Push) -> Bool } class NightPolicyVisitor: NotificationPolicy { func isTurnedOn(for email: Email) -> Bool { return false } func isTurnedOn(for sms: SMS) -> Bool { return true } func isTurnedOn(for push: Push) -> Bool { return false } var description: String { return "Night Policy Visitor" } } class DefaultPolicyVisitor: NotificationPolicy { func isTurnedOn(for email: Email) -> Bool { return true } func isTurnedOn(for sms: SMS) -> Bool { return true } func isTurnedOn(for push: Push) -> Bool { return true } var description: String { return "Default Policy Visitor" } } class BlackListVisitor: NotificationPolicy { private var bannedEmails = [String]() private var bannedPhones = [String]() private var bannedUsernames = [String]() init(emails: [String], phones: [String], usernames: [String]) { self.bannedEmails = emails self.bannedPhones = phones self.bannedUsernames = usernames } func isTurnedOn(for email: Email) -> Bool { return bannedEmails.contains(email.emailOfSender) } func isTurnedOn(for sms: SMS) -> Bool { return bannedPhones.contains(sms.phoneNumberOfSender) } func isTurnedOn(for push: Push) -> Bool { return bannedUsernames.contains(push.usernameOfSender) } var description: String { return "Black List Visitor" } } class VisitorRealWorld: XCTestCase { func testVisitorRealWorld() { let email = Email(emailOfSender: "some@email.com") let sms = SMS(phoneNumberOfSender: "+3806700000") let push = Push(usernameOfSender: "Spammer") let notifications: [Notification] = [email, sms, push] clientCode(handle: notifications, with: DefaultPolicyVisitor()) clientCode(handle: notifications, with: NightPolicyVisitor()) } } extension VisitorRealWorld { /// Client code traverses notifications with visitors and checks whether a /// notification is in a blacklist and should be shown in accordance with a /// current SilencePolicy func clientCode(handle notifications: [Notification], with policy: NotificationPolicy) { let blackList = createBlackList() print("\nClient: Using \(policy.description) and \(blackList.description)") notifications.forEach { item in guard !item.accept(visitor: blackList) else { print("\tWARNING: " + item.description + " is in a black list") return } if item.accept(visitor: policy) { print("\t" + item.description + " notification will be shown") } else { print("\t" + item.description + " notification will be silenced") } } } private func createBlackList() -> BlackListVisitor { return BlackListVisitor(emails: ["banned@email.com"], phones: ["000000000", "1234325232"], usernames: ["Spammer"]) } } ``` -------------------------------- ### Facade Conceptual Example in C# Source: https://refactoring.guru/design-patterns/facade/csharp/example Demonstrates the structure of the Facade pattern, including the Facade class, subsystems, and client interaction. It shows how the Facade delegates requests to subsystems and manages their lifecycle. ```csharp using System; namespace RefactoringGuru.DesignPatterns.Facade.Conceptual { // The Facade class provides a simple interface to the complex logic of one // or several subsystems. The Facade delegates the client requests to the // appropriate objects within the subsystem. The Facade is also responsible // for managing their lifecycle. All of this shields the client from the // undesired complexity of the subsystem. public class Facade { protected Subsystem1 _subsystem1; protected Subsystem2 _subsystem2; public Facade(Subsystem1 subsystem1, Subsystem2 subsystem2) { this._subsystem1 = subsystem1; this._subsystem2 = subsystem2; } // The Facade's methods are convenient shortcuts to the sophisticated // functionality of the subsystems. However, clients get only to a // fraction of a subsystem's capabilities. public string Operation() { string result = "Facade initializes subsystems:\n"; result += this._subsystem1.operation1(); result += this._subsystem2.operation1(); result += "Facade orders subsystems to perform the action:\n"; result += this._subsystem1.operationN(); result += this._subsystem2.operationZ(); return result; } } // The Subsystem can accept requests either from the facade or client // directly. In any case, to the Subsystem, the Facade is yet another // client, and it's not a part of the Subsystem. public class Subsystem1 { public string operation1() { return "Subsystem1: Ready!\n"; } public string operationN() { return "Subsystem1: Go!\n"; } } // Some facades can work with multiple subsystems at the same time. public class Subsystem2 { public string operation1() { return "Subsystem2: Get ready!\n"; } public string operationZ() { return "Subsystem2: Fire!\n"; } } class Client { // The client code works with complex subsystems through a simple // interface provided by the Facade. When a facade manages the lifecycle // of the subsystem, the client might not even know about the existence // of the subsystem. This approach lets you keep the complexity under // control. public static void ClientCode(Facade facade) { Console.Write(facade.Operation()); } } class Program { static void Main(string[] args) { // The client code may have some of the subsystem's objects already // created. In this case, it might be worthwhile to initialize the // Facade with these objects instead of letting the Facade create // new instances. Subsystem1 subsystem1 = new Subsystem1(); Subsystem2 subsystem2 = new Subsystem2(); Facade facade = new Facade(subsystem1, subsystem2); Client.ClientCode(facade); } } } ``` -------------------------------- ### Execution Result of State Pattern Example Source: https://refactoring.guru/design-patterns/state/ruby/example This output shows the execution flow of the conceptual State pattern example in Ruby. It demonstrates the context transitions between states and the handling of requests. ```text Context: Transition to ConcreteStateA ConcreteStateA handles request1. ConcreteStateA wants to change the state of the context. Context: Transition to ConcreteStateB ConcreteStateB handles request2. ConcreteStateB wants to change the state of the context. Context: Transition to ConcreteStateA ```