### Output of Conceptual Strategy Pattern Example in Swift Source: https://refactoring.guru/es/design-patterns/strategy/swift/example Shows the execution result of the conceptual Strategy pattern example, demonstrating normal and reverse sorting. ```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 ``` -------------------------------- ### Conceptual Example of Facade Pattern in C++ Source: https://refactoring.guru/es/design-patterns/facade/cpp/example Illustrates the structure of the Facade pattern, showing how subsystems interact through a facade class. This example manages subsystem lifecycle and delegates client requests. ```cpp /** * 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. */ class Subsystem1 { public: std::string Operation1() const { return "Subsystem1: Ready!\n"; } // ... std::string OperationN() const { return "Subsystem1: Go!\n"; } }; /** * Some facades can work with multiple subsystems at the same time. */ class Subsystem2 { public: std::string Operation1() const { return "Subsystem2: Get ready!\n"; } // ... std::string OperationZ() const { return "Subsystem2: Fire!\n"; } }; /** * 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. */ class Facade { protected: Subsystem1 *subsystem1_; Subsystem2 *subsystem2_; /** * Depending on your application's needs, you can provide the Facade with * existing subsystem objects or force the Facade to create them on its own. */ public: /** * In this case we will delegate the memory ownership to Facade Class */ Facade( Subsystem1 *subsystem1 = nullptr, Subsystem2 *subsystem2 = nullptr) { this->subsystem1_ = subsystem1 ?: new Subsystem1; this->subsystem2_ = subsystem2 ?: new Subsystem2; } ~Facade() { delete subsystem1_; delete 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. */ std::string Operation() { std::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 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. */ void ClientCode(Facade *facade) { // ... std::cout << facade->Operation(); // ... } /** * 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. */ int main() { Subsystem1 *subsystem1 = new Subsystem1; Subsystem2 *subsystem2 = new Subsystem2; Facade *facade = new Facade(subsystem1, subsystem2); ClientCode(facade); delete facade; return 0; } ``` -------------------------------- ### Real-world Example: Social Network Connectors Source: https://refactoring.guru/es/design-patterns/factory-method/php/example This example illustrates the Factory Method pattern's application in creating social network connectors. It allows for creating posts and logging in without coupling client code to specific network classes. ```text In this example, the **Factory Method** pattern provides an interface for creating connectors in social networks, which can be used to log into the network, create posts, and potentially perform other activities; all without coupling the client code to a particular social network class. ``` -------------------------------- ### Output of the Adapter Pattern Example Source: https://refactoring.guru/es/design-patterns/adapter/python/example This output shows the result of running the conceptual Adapter pattern example in Python. It illustrates how the client code interacts with both the Target and the Adapter, which translates the Adaptee's specific request. ```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. ``` -------------------------------- ### Conceptual Example of Bridge Pattern in PHP Source: https://refactoring.guru/es/design-patterns/bridge/php/example Illustrates the core structure of the Bridge pattern, showing how an abstraction maintains a reference to an implementation and delegates operations. This example requires no special setup. ```php implementation = $implementation; } public function operation(): string { return "Abstraction: Base operation with:\n" . $this->implementation->operationImplementation(); } } /** * You can extend the Abstraction without changing the Implementation classes. */ class ExtendedAbstraction extends Abstraction { public function operation(): string { return "ExtendedAbstraction: Extended operation with:\n" . $this->implementation->operationImplementation(); } } /** * The Implementation defines the interface for all implementation classes. It * doesn't have to match the Abstraction's interface. In fact, the two * interfaces can be entirely different. Typically the Implementation interface * provides only primitive operations, while the Abstraction defines higher- * level operations based on those primitives. */ interface Implementation { public function operationImplementation(): string; } /** * Each Concrete Implementation corresponds to a specific platform and * implements the Implementation interface using that platform's API. */ class ConcreteImplementationA implements Implementation { public function operationImplementation(): string { return "ConcreteImplementationA: Here's the result on the platform A.\n"; } } class ConcreteImplementationB implements Implementation { public function operationImplementation(): string { return "ConcreteImplementationB: Here's the result on the platform B.\n"; } } /** * Except for the initialization phase, where an Abstraction object gets linked * with a specific Implementation object, the client code should only depend on * the Abstraction class. This way the client code can support any abstraction- * implementation combination. */ function clientCode(Abstraction $abstraction) { // ... echo $abstraction->operation(); // ... } /** * The client code should be able to work with any pre-configured abstraction- * implementation combination. */ $implementation = new ConcreteImplementationA(); $abstraction = new Abstraction($implementation); clientCode($abstraction); echo "\n"; $implementation = new ConcreteImplementationB(); $abstraction = new ExtendedAbstraction($implementation); clientCode($abstraction); ``` -------------------------------- ### Main Execution Logic Source: https://refactoring.guru/es/design-patterns/adapter/go/example Demonstrates the usage of both the native Mac implementation and the Windows adapter. ```go package main func main() { client := &Client{} mac := &Mac{} client.InsertLightningConnectorIntoComputer(mac) windowsMachine := &Windows{} windowsMachineAdapter := &WindowsAdapter{ windowMachine: windowsMachine, } client.InsertLightningConnectorIntoComputer(windowsMachineAdapter) } ``` -------------------------------- ### Rust Iterator Filtering Example Source: https://refactoring.guru/es/design-patterns/strategy/rust/example This snippet demonstrates a common use of functional programming in Rust, similar to the Strategy pattern, by filtering an iterator to keep only positive numbers. It requires no special setup beyond standard library features. ```Rust let a = [0i32, 1, 2]; let mut iter = a.iter().filter(|x| x.is_positive()); ``` -------------------------------- ### Example 5: Reset and Recovery Source: https://refactoring.guru/es/design-patterns/memento/php/example Illustrates resetting configuration to defaults and then restoring it from a previous backup. ```php Array ( [maintenance_mode] => [theme] => light [debug] => ) ``` ```php Array ( [maintenance_mode] => [theme] => light [seo] => Array ( [title] => Best Products Online [description] => Find the best products at great prices! [keywords] => products, online, shopping, deals ) [debug] => [max_users] => 1000 [analytics] => Array ( [google_id] => GA-123456 [facebook_pixel] => FB-789012 ) ) ``` -------------------------------- ### PHP Server and Middleware Setup Source: https://refactoring.guru/es/design-patterns/chain-of-responsibility/php/example Sets up a server and registers users. It then constructs a middleware chain including throttling, user existence, and role checking, before setting it on the server. ```php $server->register("admin@example.com", "admin_pass"); $server->register("user@example.com", "user_pass"); // All middleware are chained. The client can build various configurations of // chains depending on its needs. $middleware = new ThrottlingMiddleware(2); $middleware ->linkWith(new UserExistsMiddleware($server)) ->linkWith(new RoleCheckMiddleware()); // The server gets a chain from the client code. $server->setMiddleware($middleware); ``` -------------------------------- ### Output of Mediator Pattern Example Source: https://refactoring.guru/es/design-patterns/mediator/cpp/example Shows the expected output when the C++ Mediator pattern conceptual example is executed. ```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. ``` -------------------------------- ### Configure and Run Demo Source: https://refactoring.guru/es/design-patterns/abstract-factory/java/example The Demo class initializes the application with the appropriate factory based on the environment. ```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(); } } ``` -------------------------------- ### Output of State Pattern Example Source: https://refactoring.guru/es/design-patterns/state/python/example Shows the execution flow and state transitions when running the conceptual State pattern example in Python. ```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 ``` -------------------------------- ### Output of Memento Example Source: https://refactoring.guru/es/design-patterns/memento/swift/example The execution output of the Swift Memento pattern example, showing the saved states and the result after 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} ``` -------------------------------- ### Application Class Example Source: https://refactoring.guru/es/design-patterns/builder Client code demonstrating how to use the Director and Builder to create different products. It shows instantiating builders, passing them to the director, and retrieving the final products. ```php class Application { public function makeCar(): void { $director = new Director(); $builder = new CarBuilder(); $director->constructSportsCar($builder); $car = $builder->getProduct(); $builder = new CarManualBuilder(); $director->constructSportsCar($builder); $manual = $builder->getProduct(); // The final product is often retrieved from a builder object, as the director // doesn't know about and doesn't depend on concrete builders and products. } } ``` -------------------------------- ### Output of State Pattern Example Source: https://refactoring.guru/es/design-patterns/state/cpp/example This output shows the execution flow of the State pattern example in C++, illustrating the transitions between ConcreteStateA and ConcreteStateB. ```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. ``` -------------------------------- ### Execute Client Demo in Java Source: https://refactoring.guru/es/design-patterns/command/java/example Entry point for the application that initializes the editor instance. ```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(); } } ``` -------------------------------- ### Example 6: History Management Source: https://refactoring.guru/es/design-patterns/memento/php/example Shows how to view available configuration backups and clear the history. ```php [0] 2025-07-28 15:04:16 / (5 items, maintenance: ) ``` ```php No backups available. ``` -------------------------------- ### Execution output of the Mediator pattern example Source: https://refactoring.guru/es/design-patterns/mediator/go/example Shows the sequence of events and messages printed to the console during the execution of the Go Mediator pattern example. ```text PassengerTrain: Arrived FreightTrain: Arrival blocked, waiting PassengerTrain: Leaving FreightTrain: Arrival permitted FreightTrain: Arrived ``` -------------------------------- ### Initialize Repository Source: https://refactoring.guru/es/design-patterns/observer/php/example Initializes the repository by loading user records from a specified file and broadcasting an 'users:init' event. ```php $repository->initialize(__DIR__ . "/users.csv"); ``` -------------------------------- ### Client Code Example Source: https://refactoring.guru/es/design-patterns/builder/cpp/example Demonstrates how a client interacts with the Director and Concrete Builder to create a product. Note the use of raw pointers for simplicity. ```cpp void ClientCode(Director& director) { ConcreteBuilder1* builder = new ConcreteBuilder1(); director.set_builder(builder); std::cout << "Standard basic product:\n"; director.BuildMinimalViableProduct(); ``` -------------------------------- ### Output of Strategy Pattern Example Source: https://refactoring.guru/es/design-patterns/strategy/ruby/example This output shows the result of executing the conceptual Strategy pattern example in Ruby, demonstrating both normal and reverse sorting. ```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 ``` -------------------------------- ### Application Initialization with Proxy Source: https://refactoring.guru/es/design-patterns/proxy Demonstrates how the application can initialize and use the proxy object instead of the real service, enabling caching and lazy loading transparently. ```pseudocode // The application can set up proxies on the fly. class Application is method init() is aYouTubeService = new ThirdPartyYouTubeClass() aYouTubeProxy = new CachedYouTubeClass(aYouTubeService) manager = new YouTubeManager(aYouTubeProxy) manager.reactOnUserInput() ``` -------------------------------- ### Conceptual Mediator Example Output in Swift Source: https://refactoring.guru/es/design-patterns/mediator/swift/example Shows the expected output when the conceptual Mediator example is executed, demonstrating how the mediator coordinates component interactions. ```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. ``` -------------------------------- ### Output of Facade Pattern Example Source: https://refactoring.guru/es/design-patterns/facade/cpp/example The expected output when running the conceptual Facade pattern example in C++. It demonstrates the simplified interaction provided by the facade. ```text Facade initializes subsystems: Subsystem1: Ready! Subsystem2: Get ready! Facade orders subsystems to perform the action: Subsystem1: Go! Subsystem2: Fire! ``` -------------------------------- ### Execute Client Code in Go Source: https://refactoring.guru/es/design-patterns/flyweight/go/example Demonstrates the initialization of the game and iteration over the dress factory instance to display dress colors. ```go package main import "fmt" func main() { game := newGame() //Add Terrorist game.addTerrorist(TerroristDressType) game.addTerrorist(TerroristDressType) game.addTerrorist(TerroristDressType) game.addTerrorist(TerroristDressType) //Add CounterTerrorist game.addCounterTerrorist(CounterTerrroristDressType) game.addCounterTerrorist(CounterTerrroristDressType) game.addCounterTerrorist(CounterTerrroristDressType) dressFactoryInstance := getDressFactorySingleInstance() for dressType, dress := range dressFactoryInstance.dressMap { fmt.Printf("DressColorType: %s\nDressColor: %s\n", dressType, dress.getColor()) } } ``` -------------------------------- ### Initialize Proxy Demo Source: https://refactoring.guru/es/design-patterns/proxy/java/example Compares performance between a direct service call and a proxied service call. ```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; } } ``` -------------------------------- ### Output of the Bridge Pattern Example Source: https://refactoring.guru/es/design-patterns/bridge/cpp/example The expected output when running the conceptual C++ example of the Bridge pattern, demonstrating the results from different concrete implementations. ```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. ``` -------------------------------- ### Factory Method Output Example Source: https://refactoring.guru/es/design-patterns/factory-method/cpp/example This output demonstrates the execution of the Factory Method pattern, showing how different creators produce different products and how the client remains unaware of the specific product types. ```text App: Launched with the ConcreteCreator1. Client: I'm not aware of the creator's class, but it still works. Creator: The same creator's code has just worked with {Result of the ConcreteProduct1} App: Launched with the ConcreteCreator2. Client: I'm not aware of the creator's class, but it still works. Creator: The same creator's code has just worked with {Result of the ConcreteProduct2} ``` -------------------------------- ### Conceptual Example of Prototype Pattern Source: https://refactoring.guru/es/design-patterns/prototype/python/example Illustrates the structure and relationships of classes within the Prototype pattern. This example focuses on the conceptual understanding rather than a specific implementation. ```python class Prototype: def clone(self): pass class ConcretePrototypeA(Prototype): def __init__(self, data): self.data = data def clone(self): # Create a new object with the same state return ConcretePrototypeA(self.data) class ConcretePrototypeB(Prototype): def __init__(self, data, extra_data): self.data = data self.extra_data = extra_data def clone(self): # Create a new object with the same state return ConcretePrototypeB(self.data, self.extra_data) # Client code prototype_a = ConcretePrototypeA("Data A") clone_a = prototype_a.clone() prototype_b = ConcretePrototypeB("Data B", "Extra B") clone_b = prototype_b.clone() print(f"Original A data: {prototype_a.data}") print(f"Cloned A data: {clone_a.data}") print(f"Original B data: {prototype_b.data}, {prototype_b.extra_data}") print(f"Cloned B data: {clone_b.data}, {clone_b.extra_data}") ``` -------------------------------- ### Execute the Proxy Pattern Source: https://refactoring.guru/es/design-patterns/proxy/rust/example Main entry point demonstrating the proxy behavior with rate limiting. ```rust mod server; use crate::server::{NginxServer, Server}; fn main() { let app_status = &"/app/status".to_string(); let create_user = &"/create/user".to_string(); let mut nginx = NginxServer::new(); let (code, body) = nginx.handle_request(app_status, "GET"); println!("Url: {}\nHttpCode: {}\nBody: {}\n", app_status, code, body); let (code, body) = nginx.handle_request(app_status, "GET"); println!("Url: {}\nHttpCode: {}\nBody: {}\n", app_status, code, body); let (code, body) = nginx.handle_request(app_status, "GET"); println!("Url: {}\nHttpCode: {}\nBody: {}\n", app_status, code, body); let (code, body) = nginx.handle_request(create_user, "POST"); println!("Url: {}\nHttpCode: {}\nBody: {}\n", create_user, code, body); let (code, body) = nginx.handle_request(create_user, "GET"); println!("Url: {}\nHttpCode: {}\nBody: {}\n", create_user, code, body); } ``` -------------------------------- ### Output of Prototype Pattern Conceptual Example Source: https://refactoring.guru/es/design-patterns/prototype/php/example The expected output when running the conceptual example of the Prototype pattern in PHP, demonstrating successful cloning of primitive fields and components. ```text Primitive field values have been carried over to a clone. Yay! Simple component has been cloned. Yay! Component with back reference has been cloned. Yay! Component with back reference is linked to the clone. Yay! ``` -------------------------------- ### Iterator Pattern C++ Example Output Source: https://refactoring.guru/es/design-patterns/iterator/cpp/example This output shows the result of running the C++ Iterator pattern example, demonstrating traversal of integer and custom data collections. ```text ________________Iterator with int______________________________________ 0 1 2 3 4 5 6 7 8 9 ________________Iterator with custom Class______________________________ 100 1000 10000 ``` -------------------------------- ### Initialize Memento Editor in Java Source: https://refactoring.guru/es/design-patterns/memento/java/example Sets up the editor instance and populates it with various geometric shapes. Requires the refactoring_guru.memento.example package structure. ```java package refactoring_guru.memento.example; import refactoring_guru.memento.example.editor.Editor; import refactoring_guru.memento.example.shapes.Circle; import refactoring_guru.memento.example.shapes.CompoundShape; import refactoring_guru.memento.example.shapes.Dot; import refactoring_guru.memento.example.shapes.Rectangle; import java.awt.*; public class Demo { public static void main(String[] args) { Editor editor = new Editor(); editor.loadShapes( new Circle(10, 10, 10, Color.BLUE), new CompoundShape( new Circle(110, 110, 50, Color.RED), new Dot(160, 160, Color.RED) ), new CompoundShape( new Rectangle(250, 250, 100, 100, Color.GREEN), new Dot(240, 240, Color.GREEN), new Dot(240, 360, Color.GREEN), new Dot(360, 360, Color.GREEN), new Dot(360, 240, Color.GREEN) ) ); } } ``` -------------------------------- ### Output of Template Method Example Source: https://refactoring.guru/es/design-patterns/template-method/ruby/example Shows the execution results of the conceptual Template Method pattern example in Ruby, demonstrating the output from both ConcreteClass1 and ConcreteClass2 when their template methods are called. ```Text Same client code can work with different subclasses: AbstractClass says: I am doing the bulk of the work ConcreteClass1 says: Implemented Operation1 AbstractClass says: But I let subclasses override some operations ConcreteClass1 says: Implemented Operation2 AbstractClass says: But I am doing the bulk of the work anyway Same client code can work with different subclasses: AbstractClass says: I am doing the bulk of the work ConcreteClass2 says: Implemented Operation1 AbstractClass says: But I let subclasses override some operations ConcreteClass2 says: Overridden Hook1 ConcreteClass2 says: Implemented Operation2 AbstractClass says: But I am doing the bulk of the work anyway ``` -------------------------------- ### Output of Prototype Pattern Example in Go Source: https://refactoring.guru/es/design-patterns/prototype/go/example Shows the expected output when running the client code. It illustrates the original file system hierarchy and its cloned version, with names appended by '_clone'. ```text Printing hierarchy for Folder2 Folder2 Folder1 File1 File2 File3 Printing hierarchy for clone Folder Folder2_clone Folder1_clone File1_clone File2_clone File3_clone ``` -------------------------------- ### Implementación del patrón Facade en pseudocódigo Source: https://refactoring.guru/es/design-patterns/facade Ejemplo de cómo encapsular un framework complejo de conversión de vídeo dentro de una clase fachada para simplificar su uso por parte de la aplicación. ```pseudocode // Estas son algunas de las clases de un framework de conversión // de video de un tercero. No controlamos ese código, por lo que // no podemos simplificarlo. class VideoFile // ... class OggCompressionCodec // ... class MPEG4CompressionCodec // ... class CodecFactory // ... class BitrateReader // ... class AudioMixer // ... // Creamos una clase fachada para esconder la complejidad del // framework tras una interfaz simple. Es una solución de // equilibrio entre funcionalidad y simplicidad. class VideoConverter is method convert(filename, format):File is file = new VideoFile(filename) sourceCodec = (new CodecFactory).extract(file) if (format == "mp4") destinationCodec = new MPEG4CompressionCodec() else destinationCodec = new OggCompressionCodec() buffer = BitrateReader.read(filename, sourceCodec) result = BitrateReader.convert(buffer, destinationCodec) result = (new AudioMixer()).fix(result) return new File(result) // Las clases Application no dependen de un millón de clases // proporcionadas por el complejo framework. Además, si decides // cambiar los frameworks, sólo tendrás de volver a escribir la // clase fachada. class Application is method main() is convertor = new VideoConverter() mp4 = convertor.convert("funny-cats-video.ogg", "mp4") mp4.save() ``` -------------------------------- ### Conceptual Example of Prototype Pattern in C++ Source: https://refactoring.guru/es/design-patterns/prototype/cpp/example Illustrates the structure of the Prototype design pattern, focusing on its components and their relationships. This example demonstrates how to clone objects using a common interface. ```cpp using std::string; // Prototype Design Pattern // // Intent: Lets you copy existing objects without making your code dependent on // their classes. enum Type { PROTOTYPE_1 = 0, PROTOTYPE_2 }; /** * The example class that has cloning ability. We'll see how the values of field * with different types will be cloned. */ class Prototype { protected: string prototype_name_; float prototype_field_; public: Prototype() {} Prototype(string prototype_name) : prototype_name_(prototype_name) { } virtual ~Prototype() {} virtual Prototype *Clone() const = 0; virtual void Method(float prototype_field) { this->prototype_field_ = prototype_field; std::cout << "Call Method from " << prototype_name_ << " with field : " << prototype_field << std::endl; } }; /** * ConcretePrototype1 is a Sub-Class of Prototype and implement the Clone Method * In this example all data members of Prototype Class are in the Stack. If you * have pointers in your properties for ex: String* name_ ,you will need to * implement the Copy-Constructor to make sure you have a deep copy from the * clone method */ class ConcretePrototype1 : public Prototype { private: float concrete_prototype_field1_; public: ConcretePrototype1(string prototype_name, float concrete_prototype_field) : Prototype(prototype_name), concrete_prototype_field1_(concrete_prototype_field) { } /** * Notice that Clone method return a Pointer to a new ConcretePrototype1 * replica. so, the client (who call the clone method) has the responsability * to free that memory. If you have smart pointer knowledge you may prefer to * use unique_pointer here. */ Prototype *Clone() const override { return new ConcretePrototype1(*this); } }; class ConcretePrototype2 : public Prototype { private: float concrete_prototype_field2_; public: ConcretePrototype2(string prototype_name, float concrete_prototype_field) : Prototype(prototype_name), concrete_prototype_field2_(concrete_prototype_field) { } Prototype *Clone() const override { return new ConcretePrototype2(*this); } }; /** * In PrototypeFactory you have two concrete prototypes, one for each concrete * prototype class, so each time you want to create a bullet , you can use the * existing ones and clone those. */ class PrototypeFactory { private: std::unordered_map> prototypes_; public: PrototypeFactory() { prototypes_[Type::PROTOTYPE_1] = new ConcretePrototype1("PROTOTYPE_1 ", 50.f); prototypes_[Type::PROTOTYPE_2] = new ConcretePrototype2("PROTOTYPE_2 ", 60.f); } /** * Be carefull of free all memory allocated. Again, if you have smart pointers * knowelege will be better to use it here. */ ~PrototypeFactory() { delete prototypes_[Type::PROTOTYPE_1]; delete prototypes_[Type::PROTOTYPE_2]; } /** * Notice here that you just need to specify the type of the prototype you * want and the method will create from the object with this type. */ Prototype *CreatePrototype(Type type) { return prototypes_[type]->Clone(); } }; void Client(PrototypeFactory &prototype_factory) { std::cout << "Let's create a Prototype 1\n"; Prototype *prototype = prototype_factory.CreatePrototype(Type::PROTOTYPE_1); prototype->Method(90); delete prototype; std::cout << "\n"; std::cout << "Let's create a Prototype 2 \n"; prototype = prototype_factory.CreatePrototype(Type::PROTOTYPE_2); prototype->Method(10); delete prototype; } int main() { PrototypeFactory *prototype_factory = new PrototypeFactory(); Client(*prototype_factory); delete prototype_factory; return 0; } ``` -------------------------------- ### Execute Client Demo Source: https://refactoring.guru/es/design-patterns/bridge/java/example Client code demonstrating the usage of different remotes with various devices. ```java package refactoring_guru.bridge.example; import refactoring_guru.bridge.example.devices.Device; import refactoring_guru.bridge.example.devices.Radio; import refactoring_guru.bridge.example.devices.Tv; import refactoring_guru.bridge.example.remotes.AdvancedRemote; import refactoring_guru.bridge.example.remotes.BasicRemote; public class Demo { public static void main(String[] args) { testDevice(new Tv()); testDevice(new Radio()); } public static void testDevice(Device device) { System.out.println("Tests with basic remote."); BasicRemote basicRemote = new BasicRemote(device); basicRemote.power(); device.printStatus(); System.out.println("Tests with advanced remote."); AdvancedRemote advancedRemote = new AdvancedRemote(device); advancedRemote.power(); advancedRemote.mute(); device.printStatus(); } } ``` -------------------------------- ### Output of Observer Pattern Example in Ruby Source: https://refactoring.guru/es/design-patterns/observer/ruby/example Shows the console output generated by running the conceptual Observer pattern example, demonstrating how observers react to state changes in the subject. ```text Subject: Attached an observer. Subject: Attached an observer. Subject: I'm doing something important. Subject: My state has just changed to: 1 Subject: Notifying observers... ConcreteObserverA: Reacted to the event Subject: I'm doing something important. Subject: My state has just changed to: 10 Subject: Notifying observers... ConcreteObserverB: Reacted to the event Subject: I'm doing something important. Subject: My state has just changed to: 2 Subject: Notifying observers... ConcreteObserverB: Reacted to the event ```