Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Refactoring Guru
https://refactoringguru.cn/
Admin
Refactoring Guru 提供免费在线资源,用于学习代码重构、设计模式、SOLID原则以及其他智能编程主题,帮助开发者理解它们之间的相互关联。
Tokens:
376,864
Snippets:
2,107
Trust Score:
8
Update:
3 months ago
Context
Chat
Benchmark
71
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Initialize Memento Demo in Java Source: https://refactoringguru.cn/design-patterns/memento/java/example Demonstrates the setup of an Editor instance and loading various shapes to prepare for state management. ```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) ) ); } } ``` -------------------------------- ### Execution Output Example Source: https://refactoringguru.cn/design-patterns/chain-of-responsibility/java/example Sample console output demonstrating successful authorization and handling of failed login attempts. ```text Enter email: admin@example.com Input password: admin_pass Hello, admin! Authorization have been successful! Enter email: wrong@example.com Input password: wrong_pass This email is not registered! Enter email: wrong@example.com Input password: wrong_pass This email is not registered! Enter email: wrong@example.com Input password: wrong_pass Request limit exceeded! ``` -------------------------------- ### State Pattern Usage Demonstration Source: https://refactoringguru.cn/design-patterns/state/php/example Example usage showing how to instantiate the context and trigger state transitions, including error handling for invalid transitions. ```php try { echo "=== Invoice State Pattern Demo ===\n\n"; // Create a new invoice (starts in draft state) $invoice = new Invoice(1001, 1500.00); echo "Created invoice: " . json_encode($invoice->getInfo()) . "\n\n"; // Scenario 1: Draft -> Open -> Paid echo "--- Scenario 1: Draft -> Open -> Paid ---\n"; $invoice->finalize(); // Draft -> Open echo "Current state: " . $invoice->getStateName() . "\n"; $invoice->pay(); // Open -> Paid echo "Current state: " . $invoice->getStateName() . "\n"; // Try to pay again (should fail) try { $invoice->pay(); } catch (InvalidStateTransitionException $e) { echo "Expected error: " . $e->getMessage() . "\n"; } echo "\n--- Scenario 2: Draft -> Open -> Void ---\n"; $invoice2 = new Invoice(1002, 750.00); $invoice2->finalize(); // Draft -> Open $invoice2->void(); // Open -> Void echo "Invoice 2 state: " . $invoice2->getStateName() . "\n"; ``` -------------------------------- ### Singleton Execution Output Source: https://refactoringguru.cn/design-patterns/singleton/php/example The expected output after running the Singleton implementation example. ```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! ``` -------------------------------- ### Form Output Example Source: https://refactoringguru.cn/design-patterns/composite/php/example The resulting HTML output after rendering the product form. ```html <form action="/product/add"> <h3>Add product</h3> <label for="name">Name</label> <input name="name" type="text" value="Apple MacBook"> <label for="description">Description</label> <input name="description" type="text" value="A decent laptop."> <fieldset><legend>Product photo</legend> <label for="caption">Caption</label> <input name="caption" type="text" value="Front photo."> <label for="image">Image</label> <input name="image" type="file" value="photo1.png"> </fieldset> </form> ``` -------------------------------- ### View Execution Output Source: https://refactoringguru.cn/design-patterns/strategy/java/example Example console output showing the interaction flow of the Strategy pattern implementation. ```text Please, select a product: 1 - Mother board 2 - CPU 3 - HDD 4 - Memory 1 Count: 2 Do you wish to continue selecting products? Y/N: y Please, select a product: 1 - Mother board 2 - CPU 3 - HDD 4 - Memory 2 Count: 1 Do you wish to continue selecting products? Y/N: n Please, select a payment method: 1 - PalPay 2 - Credit Card 1 Enter the user's email: user@example.com Enter the password: qwerty Wrong email or password! Enter user email: amanda@ya.com Enter password: amanda1985 Data verification has been successful. Pay 6250 units or Continue shopping? P/C: p Paying 6250 using PayPal. Payment has been successful. ``` -------------------------------- ### Template Method Real-World Example in Swift Source: https://refactoringguru.cn/design-patterns/template-method/swift/example Demonstrates the Template Method pattern using a permission access workflow for various hardware components. ```swift import XCTest import AVFoundation import CoreLocation import Photos class TemplateMethodRealWorld: XCTestCase { /// A good example of Template Method is a life cycle of UIViewController func testTemplateMethodReal() { let accessors = [CameraAccessor(), MicrophoneAccessor(), PhotoLibraryAccessor()] accessors.forEach { item in item.requestAccessIfNeeded({ status in let message = status ? "You have access to " : "You do not have access to " print(message + item.description + "\n") }) } } } class PermissionAccessor: CustomStringConvertible { typealias Completion = (Bool) -> () func requestAccessIfNeeded(_ completion: @escaping Completion) { guard !hasAccess() else { completion(true); return } willReceiveAccess() requestAccess { status in status ? self.didReceiveAccess() : self.didRejectAccess() completion(status) } } func requestAccess(_ completion: @escaping Completion) { fatalError("Should be overridden") } func hasAccess() -> Bool { fatalError("Should be overridden") } var description: String { return "PermissionAccessor" } /// Hooks func willReceiveAccess() {} func didReceiveAccess() {} func didRejectAccess() {} } class CameraAccessor: PermissionAccessor { override func requestAccess(_ completion: @escaping Completion) { AVCaptureDevice.requestAccess(for: .video) { status in return completion(status) } } override func hasAccess() -> Bool { return AVCaptureDevice.authorizationStatus(for: .video) == .authorized } override var description: String { return "Camera" } } class MicrophoneAccessor: PermissionAccessor { override func requestAccess(_ completion: @escaping Completion) { AVAudioSession.sharedInstance().requestRecordPermission { status in completion(status) } } override func hasAccess() -> Bool { return AVAudioSession.sharedInstance().recordPermission == .granted } override var description: String { return "Microphone" } } class PhotoLibraryAccessor: PermissionAccessor { override func requestAccess(_ completion: @escaping Completion) { PHPhotoLibrary.requestAuthorization { status in completion(status == .authorized) } } override func hasAccess() -> Bool { return PHPhotoLibrary.authorizationStatus() == .authorized } override var description: String { return "PhotoLibrary" } override func didReceiveAccess() { /// We want to track how many people give access to the PhotoLibrary. print("PhotoLibrary Accessor: Receive access. Updating analytics...") } override func didRejectAccess() { /// ... and also we want to track how many people rejected access. print("PhotoLibrary Accessor: Rejected with access. Updating analytics...") } } ``` -------------------------------- ### Facade Pattern Implementation in Swift Source: https://refactoringguru.cn/design-patterns/facade/swift/example This example demonstrates using a UIImageView extension as a facade to simplify image downloading from a complex ImageDownloader subsystem. ```swift import XCTest /// Facade Design Pattern /// /// Intent: Provides a simplified interface to a library, a framework, or any /// other complex set of classes. class FacadeRealWorld: XCTestCase { /// In the real project, you probably will use third-party libraries. For /// instance, to download images. /// /// Therefore, facade and wrapping it is a good way to use a third-party API /// in the client code. Even if it is your own library that is connected to /// a project. /// /// The benefits here are: /// /// 1) If you need to change a current image downloader it should be done /// only in the one place of a project. A number of lines of the client code /// will stay work. /// /// 2) The facade provides an access to a fraction of a functionality that /// fits most client needs. Moreover, it can set frequently used or default /// parameters. func testFacadeRealWorld() { let imageView = UIImageView() print("Let's set an image for the image view") clientCode(imageView) print("Image has been set") XCTAssert(imageView.image != nil) } fileprivate func clientCode(_ imageView: UIImageView) { let url = URL(string: "www.example.com/logo") imageView.downloadImage(at: url) } } private extension UIImageView { /// This extension plays a facade role. func downloadImage(at url: URL?) { print("Start downloading...") let placeholder = UIImage(named: "placeholder") ImageDownloader().loadImage(at: url, placeholder: placeholder, completion: { image, error in print("Handle an image...") /// Crop, cache, apply filters, whatever... self.image = image }) } } private class ImageDownloader { /// Third-party library or your own solution (subsystem) typealias Completion = (UIImage, Error?) -> () typealias Progress = (Int, Int) -> () func loadImage(at url: URL?, placeholder: UIImage? = nil, progress: Progress? = nil, completion: Completion) { /// ... Set up a network stack /// ... Downloading an image /// ... completion(UIImage(), nil) } } ``` -------------------------------- ### Builder Pattern Implementation in Pseudocode Source: https://refactoringguru.cn/design-patterns/builder This example demonstrates how to use a Director and multiple Builders to construct complex objects like Cars and their corresponding Manuals. ```pseudocode // 只有当产品较为复杂且需要详细配置时,使用生成器模式才有意义。下面的两个 // 产品尽管没有同样的接口,但却相互关联。 class Car is // 一辆汽车可能配备有 GPS 设备、行车电脑和几个座位。不同型号的汽车( // 运动型轿车、SUV 和敞篷车)可能会安装或启用不同的功能。 class Manual is // 用户使用手册应该根据汽车配置进行编制,并介绍汽车的所有功能。 // 生成器接口声明了创建产品对象不同部件的方法。 interface Builder is method reset() method setSeats(……) method setEngine(……) method setTripComputer(……) method setGPS(……) // 具体生成器类将遵循生成器接口并提供生成步骤的具体实现。你的程序中可能会 // 有多个以不同方式实现的生成器变体。 class CarBuilder implements Builder is private field car:Car // 一个新的生成器实例必须包含一个在后续组装过程中使用的空产品对象。 constructor CarBuilder() is this.reset() // reset(重置)方法可清除正在生成的对象。 method reset() is this.car = new Car() // 所有生成步骤都会与同一个产品实例进行交互。 method setSeats(……) is // 设置汽车座位的数量。 method setEngine(……) is // 安装指定的引擎。 method setTripComputer(……) is // 安装行车电脑。 method setGPS(……) is // 安装全球定位系统。 // 具体生成器需要自行提供获取结果的方法。这是因为不同类型的生成器可能 // 会创建不遵循相同接口的、完全不同的产品。所以也就无法在生成器接口中 // 声明这些方法(至少在静态类型的编程语言中是这样的)。 // // 通常在生成器实例将结果返回给客户端后,它们应该做好生成另一个产品的 // 准备。因此生成器实例通常会在 `getProduct(获取产品)`方法主体末尾 // 调用重置方法。但是该行为并不是必需的,你也可让生成器等待客户端明确 // 调用重置方法后再去处理之前的结果。 method getProduct():Car is product = this.car this.reset() return product // 生成器与其他创建型模式的不同之处在于:它让你能创建不遵循相同接口的产品。 class CarManualBuilder implements Builder is private field manual:Manual constructor CarManualBuilder() is this.reset() method reset() is this.manual = new Manual() method setSeats(……) is // 添加关于汽车座椅功能的文档。 method setEngine(……) is // 添加关于引擎的介绍。 method setTripComputer(……) is // 添加关于行车电脑的介绍。 method setGPS(……) is // 添加关于 GPS 的介绍。 method getProduct():Manual is // 返回使用手册并重置生成器。 // 主管只负责按照特定顺序执行生成步骤。其在根据特定步骤或配置来生成产品时 // 会很有帮助。由于客户端可以直接控制生成器,所以严格意义上来说,主管类并 // 不是必需的。 class Director is // 主管可同由客户端代码传递给自身的任何生成器实例进行交互。客户端可通 // 过这种方式改变最新组装完毕的产品的最终类型。主管可使用同样的生成步 // 骤创建多个产品变体。 method constructSportsCar(builder: Builder) is builder.reset() builder.setSeats(2) builder.setEngine(new SportEngine()) builder.setTripComputer(true) builder.setGPS(true) method constructSUV(builder: Builder) is // …… // 客户端代码会创建生成器对象并将其传递给主管,然后执行构造过程。最终结果 // 将需要从生成器对象中获取。 class Application is method makeCar() is director = new Director() CarBuilder builder = new CarBuilder() director.constructSportsCar(builder) Car car = builder.getProduct() CarManualBuilder builder = new CarManualBuilder() director.constructSportsCar(builder) // 最终产品通常需要从生成器对象中获取,因为主管不知晓具体生成器和 // 产品的存在,也不会对其产生依赖。 Manual manual = builder.getProduct() ``` -------------------------------- ### Observer Pattern Implementation in Pseudocode Source: https://refactoringguru.cn/design-patterns/observer This example demonstrates a publisher-subscriber system where an Editor notifies registered listeners of file operations. The EventManager handles the subscription logic, allowing for flexible runtime configuration. ```pseudocode // 发布者基类包含订阅管理代码和通知方法。 class EventManager is private field listeners: hash map of event types and listeners method subscribe(eventType, listener) is listeners.add(eventType, listener) method unsubscribe(eventType, listener) is listeners.remove(eventType, listener) method notify(eventType, data) is foreach (listener in listeners.of(eventType)) do listener.update(data) // 具体发布者包含一些订阅者感兴趣的实际业务逻辑。我们可以从发布者基类中扩 // 展出该类,但在实际情况下并不总能做到,因为具体发布者可能已经是子类了。 // 在这种情况下,你可用组合来修补订阅逻辑,就像我们在这里做的一样。 class Editor is public field events: EventManager private field file: File constructor Editor() is events = new EventManager() // 业务逻辑的方法可将变化通知给订阅者。 method openFile(path) is this.file = new File(path) events.notify("open", file.name) method saveFile() is file.write() events.notify("save", file.name) // …… // 这里是订阅者接口。如果你的编程语言支持函数类型,则可用一组函数来代替整 // 个订阅者的层次结构。 interface EventListener is method update(filename) // 具体订阅者会对其注册的发布者所发出的更新消息做出响应。 class LoggingListener implements EventListener is private field log: File private field message: string constructor LoggingListener(log_filename, message) is this.log = new File(log_filename) this.message = message method update(filename) is log.write(replace('%s',filename,message)) class EmailAlertsListener implements EventListener is private field email: string private field message: string constructor EmailAlertsListener(email, message) is this.email = email this.message = message method update(filename) is system.email(email, replace('%s',filename,message)) // 应用程序可在运行时配置发布者和订阅者。 class Application is method config() is editor = new Editor() logger = new LoggingListener( "/path/to/log.txt", "有人打开了文件:%s"); editor.events.subscribe("open", logger) emailAlerts = new EmailAlertsListener( "admin@example.com", "有人更改了文件:%s") editor.events.subscribe("save", emailAlerts) ``` -------------------------------- ### Execution Output Source: https://refactoringguru.cn/design-patterns/abstract-factory/java/example Example output generated by the application. ```text You create WindowsButton. You created WindowsCheckbox. ``` -------------------------------- ### Initialize Proxy Demo in Java Source: https://refactoringguru.cn/design-patterns/proxy/java/example Main entry point demonstrating the performance difference between a naive downloader and one using 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; } } ``` -------------------------------- ### Example of Non-Magical Number Source: https://refactoringguru.cn/replace-magic-number-with-symbolic-constant Demonstrates a loop counter where the purpose is self-evident. ```java for (i = 0; i < сount; i++) { ... } ``` -------------------------------- ### Client Code Demonstration Source: https://refactoringguru.cn/design-patterns/memento/php/example Demonstrates initializing the configuration manager, performing backups, modifying state, and executing undo operations. ```php echo "=== Configuration Manager with Memento Pattern Demo ===\n\n"; /** * Example 1: Basic configuration management with backup/restore */ echo "--- Example 1: Basic Configuration Management ---\n"; // Initialize configuration manager with default settings $config = new ConfigManager([ 'maintenance_mode' => false, 'theme' => 'light', 'seo' => ['title' => 'My Website', 'description' => 'Welcome to my site!'], 'debug' => false, 'max_users' => 1000 ]); // Create history manager $history = new ConfigHistory($config); echo "\nInitial configuration:\n"; print_r($config->getConfig()); /** * Example 2: Making changes with backups */ echo "\n--- Example 2: Making Changes with Backups ---\n"; // Create backup before making changes $history->backup(); // Update theme settings $config->updateConfig([ 'theme' => 'dark', 'theme_options' => ['sidebar' => 'collapsed', 'font_size' => 'large'] ]); echo "\nAfter theme update:\n"; print_r($config->getConfig()); // Create another backup $history->backup(); // Enable maintenance mode $config->enableMaintenanceMode(); echo "\nAfter enabling maintenance mode:\n"; print_r($config->getConfig()); /** * Example 3: Demonstrating undo functionality */ echo "\n--- Example 3: Undo Functionality ---\n"; // Show current history $history->showHistory(); // Undo last change (maintenance mode) echo "Undoing maintenance mode activation...\n"; $history->undo(); echo "\nAfter first undo:\n"; print_r($config->getConfig()); // Undo theme changes echo "\nUndoing theme changes...\n"; $history->undo(); echo "\nAfter second undo (back to original):\n"; print_r($config->getConfig()); /** * Example 4: Multiple configuration scenarios */ echo "\n--- Example 4: Multiple Configuration Scenarios ---\n"; ``` -------------------------------- ### Run Command Pattern Demo in Java Source: https://refactoringguru.cn/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(); } } ``` -------------------------------- ### Execution Output Source: https://refactoringguru.cn/design-patterns/factory-method/swift/example The console output generated by running the Factory Method example. ```text Info is presented over Wifi: Very important info of the presentation Info is presented over Bluetooth: Very important info of the presentation ``` -------------------------------- ### Initialize Demo Application Source: https://refactoringguru.cn/design-patterns/state/java/example The Demo class serves as the entry point to instantiate the player and initialize the user interface. ```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(); } } ``` -------------------------------- ### Example of Deeply Nested Conditionals Source: https://refactoringguru.cn/replace-nested-conditional-with-guard-clauses Illustrates the 'arrow' anti-pattern caused by excessive nesting. ```text if () { if () { do { if () { if () { if () { ... } } ... } ... } while (); ... } else { ... } } ``` -------------------------------- ### Prototype Pattern Execution Output Source: https://refactoringguru.cn/design-patterns/prototype/rust/example The expected console output after running the cloning example. ```text Circle 1: 10, 15, 10 Circle 2: 10, 15, 77 ``` -------------------------------- ### View Execution Output Source: https://refactoringguru.cn/design-patterns/memento/swift/example Displays the console output generated by the Memento conceptual example. ```text Originator: My initial state is: Super-duper-super-puper-super. Caretaker: Saving Originator's state... Originator: I'm doing something important. Originator: and my state has changed to: 1923 Caretaker: Saving Originator's state... Originator: I'm doing something important. Originator: and my state has changed to: 74FB Caretaker: Saving Originator's state... Originator: I'm doing something important. Originator: and my state has changed to: 3681 Caretaker: Here's the list of mementos: Super-duper-super-puper-super. 11:45:44 1923 11:45:44 74FB 11:45:44 Client: Now, let's rollback! Caretaker: Restoring state to: 74FB 11:45:44 Originator: My state has changed to: 74FB Client: Once more! Caretaker: Restoring state to: 1923 11:45:44 Originator: My state has changed to: 1923 ``` -------------------------------- ### Implement Client Demo in Java Source: https://refactoringguru.cn/design-patterns/strategy/java/example The Demo class acts as the client, selecting a payment strategy at runtime based on user input and executing the order process. ```java package refactoring_guru.strategy.example; import refactoring_guru.strategy.example.order.Order; import refactoring_guru.strategy.example.strategies.PayByCreditCard; import refactoring_guru.strategy.example.strategies.PayByPayPal; import refactoring_guru.strategy.example.strategies.PayStrategy; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * World first console e-commerce application. */ public class Demo { private static Map<Integer, Integer> priceOnProducts = new HashMap<>(); private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static Order order = new Order(); private static PayStrategy strategy; static { priceOnProducts.put(1, 2200); priceOnProducts.put(2, 1850); priceOnProducts.put(3, 1100); priceOnProducts.put(4, 890); } public static void main(String[] args) throws IOException { while (!order.isClosed()) { int cost; String continueChoice; do { System.out.print("Please, select a product:" + "\n" + "1 - Mother board" + "\n" + "2 - CPU" + "\n" + "3 - HDD" + "\n" + "4 - Memory" + "\n"); int choice = Integer.parseInt(reader.readLine()); cost = priceOnProducts.get(choice); System.out.print("Count: "); int count = Integer.parseInt(reader.readLine()); order.setTotalCost(cost * count); System.out.print("Do you wish to continue selecting products? Y/N: "); continueChoice = reader.readLine(); } while (continueChoice.equalsIgnoreCase("Y")); if (strategy == null) { System.out.println("Please, select a payment method:" + "\n" + "1 - PalPay" + "\n" + "2 - Credit Card"); String paymentMethod = reader.readLine(); // Client creates different strategies based on input from user, // application configuration, etc. if (paymentMethod.equals("1")) { strategy = new PayByPayPal(); } else { strategy = new PayByCreditCard(); } } // Order object delegates gathering payment data to strategy object, // since only strategies know what data they need to process a // payment. order.processOrder(strategy); System.out.print("Pay " + order.getTotalCost() + " units or Continue shopping? P/C: "); String proceed = reader.readLine(); if (proceed.equalsIgnoreCase("P")) { // Finally, strategy handles the payment. if (strategy.pay(order.getTotalCost())) { System.out.println("Payment has been successful."); } else { System.out.println("FAIL! Please, check your data."); } order.setClosed(); } } } } ``` -------------------------------- ### Execute the Bridge pattern demo Source: https://refactoringguru.cn/design-patterns/bridge/java/example Demonstrates how to use 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(); } } ``` -------------------------------- ### Execution Output Source: https://refactoringguru.cn/design-patterns/template-method/java/example Example output showing the interaction flow for posting a message via Twitter. ```text Input user name: Jhonatan Input password: qswe Input message: Hello, World! Choose social network for posting message. 1 - Facebook 2 - Twitter 2 Checking user's parameters Name: Jhonatan Password: **** .......... LogIn success on Twitter Message: 'Hello, World!' was posted on Twitter User: 'Jhonatan' was logged out from Twitter ``` -------------------------------- ### Initialize Mediator Demo in Java Source: https://refactoringguru.cn/design-patterns/mediator/java/example Entry point that registers components with the mediator and launches the GUI. ```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(); } } ``` -------------------------------- ### Facade Pattern Execution Output Source: https://refactoringguru.cn/design-patterns/facade/php/example The expected console output when running the YouTubeDownloader facade example. ```text Fetching video metadata from youtube... Saving video file to a temporary file... Processing source video... Normalizing and resizing the video to smaller dimensions... Capturing preview image... Saving video in target formats... Done! ``` -------------------------------- ### Demo Configuration and Execution Source: https://refactoringguru.cn/design-patterns/abstract-factory/java/example Configures the application at runtime by selecting the appropriate factory based on environment variables. ```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(); } } ``` -------------------------------- ### View Composite Pattern Execution Output Source: https://refactoringguru.cn/design-patterns/composite/swift/example Displays the console output generated by the conceptual example. ```text Client: I've got a simple component: Result: Leaf Client: Now I've got a composite tree: Result: Branch(Branch(Leaf Leaf) Branch(Leaf Leaf)) Client: I don't need to check the components classes even when managing the tree: Result: Branch(Branch(Leaf Leaf) Branch(Leaf Leaf) Leaf) ``` -------------------------------- ### Execute the Proxy Pattern Source: https://refactoringguru.cn/design-patterns/proxy/rust/example Main entry point demonstrating how the client interacts with the proxy. ```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); } ``` -------------------------------- ### Execution Output of Abstract Factory Example Source: https://refactoringguru.cn/design-patterns/abstract-factory/typescript/example The console output generated by running the TypeScript implementation. ```text Client: Testing client code with the first factory type... The result of the product B1. The result of the B1 collaborating with the (The result of the product A1.) Client: Testing the same client code with the second factory type... The result of the product B2. The result of the B2 collaborating with the (The result of the product A2.) ``` -------------------------------- ### Client Code for Template Method Source: https://refactoringguru.cn/design-patterns/template-method/java/example Demonstrates the initialization of network objects and the execution of the post method based on user input. ```java package refactoring_guru.template_method.example; import refactoring_guru.template_method.example.networks.Facebook; import refactoring_guru.template_method.example.networks.Network; import refactoring_guru.template_method.example.networks.Twitter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Demo class. Everything comes together here. */ public class Demo { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Network network = null; System.out.print("Input user name: "); String userName = reader.readLine(); System.out.print("Input password: "); String password = reader.readLine(); // Enter the message. System.out.print("Input message: "); String message = reader.readLine(); System.out.println("\nChoose social network for posting message.\n" + "1 - Facebook\n" + "2 - Twitter"); int choice = Integer.parseInt(reader.readLine()); // Create proper network object and send the message. if (choice == 1) { network = new Facebook(userName, password); } else if (choice == 2) { network = new Twitter(userName, password); } network.post(message); } } ``` -------------------------------- ### Main Implementation of Decorator Source: https://refactoringguru.cn/design-patterns/decorator/rust/example A complete example showing the initialization and usage of a buffered reader in a Rust program. ```rust use std::io::{BufReader, Cursor, Read}; fn main() { let mut buf = [0u8; 10]; // A buffered reader decorates a vector reader which wraps input data. let mut input = BufReader::new(Cursor::new("Input data")); input.read(&mut buf).ok(); print!("Read from a buffered reader: "); for byte in buf { print!("{}", char::from(byte)); } println!(); } ``` -------------------------------- ### Main Application Logic Source: https://refactoringguru.cn/design-patterns/state/rust/example Sets up the Cursive UI and handles state transitions via the execute function. ```rust 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::<TextView>("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 }); } ``` -------------------------------- ### Client Demo Code Source: https://refactoringguru.cn/design-patterns/facade/java/example Demonstrates how the client uses the facade to perform a video conversion. ```java package refactoring_guru.facade.example; import refactoring_guru.facade.example.facade.VideoConversionFacade; import java.io.File; public class Demo { public static void main(String[] args) { VideoConversionFacade converter = new VideoConversionFacade(); File mp4Video = converter.convertVideo("youtubevideo.ogg", "mp4"); // ... } } ``` -------------------------------- ### Fluent Interface Example Source: https://refactoringguru.cn/design-patterns/builder/rust/example Demonstrates method chaining for object construction, which is often confused with the Builder pattern. ```rust let car = Car::default().places(5).gas(30) ```