text
stringlengths
3
2.83k
label
int64
0
1
1. A family of related products, say: `Chair` + `Sofa` + `CoffeeTable`. 2. Several variants of this family. For example, products `Chair` + `Sofa` + `CoffeeTable` are available in these variants: `Modern`, `Victorian`, `ArtDeco`.
0
You need a way to create individual furniture objects so that they match other objects of the same family. Customers get quite mad when they receive non-matching furniture.
0
![Bridge pattern problem](https://refactoring.guru/images/patterns/diagrams/bridge/problem-en.png)
0
Suppose you have a complex class that requires a laborious configuration before it can be used. There are several common ways to configure this class, and this code is scattered through your app. To reduce the duplication, you create several subclasses and put every common configuration code into their constructors. You solved the duplication problem, but now you have lots of dummy subclasses.
0
Incompetence
1
Intent
1
At some point, you decide to improve the app by integrating a smart 3rd-party analytics library. But there’s a catch: the analytics library only works with data in JSON format.
0
Use the pattern when you have a class polluted with massive conditionals that alter how the class behaves according to the current values of the class’s fields.
0
When a user triggers the undo, the history grabs the most recent memento from the stack and passes it back to the editor, requesting a roll-back. Since the editor has full access to the memento, it changes its own state with the values taken from the memento.
0
Some of the construction steps might require different implementation when you need to build various representations of the product. For example, walls of a cabin may be built of wood, but the castle walls must be built with stone.
0
![Structure of the library before applying the Decorator pattern](https://refactoring.guru/images/patterns/diagrams/decorator/problem1-en.png)
0
It’s best to perform such reviews in a pair with an author. This way you could fix simple problems quickly and gauge the time for fixing the more difficult ones.
0
Problem
1
Real-World Analogy
1
The Memento makes the object itself responsible for creating a snapshot of its state. No other object can read the snapshot, making the original object’s state data safe and secure.
0
- Many designs start by using [Factory Method](https://refactoring.guru/pattern/factory-method) (less complicated and more customizable via subclasses) and evolve toward [Abstract Factory](https://refactoring.guru/pattern/abstract-factory), [Prototype](https://refactoring.guru/pattern/prototype), or [Builder](https://refactoring.guru/pattern/builder) (more flexible, but more complicated). - [Builder](https://refactoring.guru/pattern/builder) focuses on constructing complex objects step by step. [Abstract Factory](https://refactoring.guru/pattern/abstract-factory) specializes in creating families of related objects. _Abstract Factory_ returns the product immediately, whereas _Builder_ lets you run some additional construction steps before fetching the product. - You can use [Builder](https://refactoring.guru/pattern/builder) when creating complex [Composite](https://refactoring.guru/pattern/composite) trees because you can program its construction steps to work recursively. - You can combine [Builder](https://refactoring.guru/pattern/builder) with [Bridge](https://refactoring.guru/design-patterns/bridge): the director class plays the role of the abstraction, while different builders act as implementations. - [Abstract Factories](https://refactoring.guru/pattern/abstract-factory), [Builders](https://refactoring.guru/pattern/builder) and [Prototypes](https://refactoring.guru/pattern/prototype) can all be implemented as [Singletons](https://refactoring.guru/pattern/singleton).
0
Example of iterating over social profiles.
0
_Abstraction?_ _Implementation?_ Sound scary? Stay calm and let’s consider a simple example.
0
This can lead to the accumulation of technical debt, which is then increased when changes are merged. The more changes made in isolation, the greater the total technical debt.
0
![Document delegates the work to a state object](https://refactoring.guru/images/patterns/diagrams/state/solution-en.png)
0
- [Chain of Responsibility](https://refactoring.guru/pattern/chain-of-responsibility), [Command](https://refactoring.guru/pattern/command), [Mediator](https://refactoring.guru/pattern/mediator) and [Observer](https://refactoring.guru/pattern/observer) address various ways of connecting senders and receivers of requests: - _Chain of Responsibility_ passes a request sequentially along a dynamic chain of potential receivers until one of them handles it. - _Command_ establishes unidirectional connections between senders and receivers. - _Mediator_ eliminates direct connections between senders and receivers, forcing them to communicate indirectly via a mediator object. - _Observer_ lets receivers dynamically subscribe to and unsubscribe from receiving requests. - [Chain of Responsibility](https://refactoring.guru/pattern/chain-of-responsibility) is often used in conjunction with [Composite](https://refactoring.guru/pattern/composite). In this case, when a leaf component gets a request, it may pass it through the chain of all of the parent components down to the root of the object tree. - Handlers in [Chain of Responsibility](https://refactoring.guru/pattern/chain-of-responsibility) can be implemented as [Commands](https://refactoring.guru/pattern/command). In this case, you can execute a lot of different operations over the same context object, represented by a request. However, there’s another approach, where the request itself is a _Command_ object. In this case, you can execute the same operation in a series of different contexts linked into a chain. - [Chain of Responsibility](https://refactoring.guru/pattern/chain-of-responsibility) and [Decorator](https://refactoring.guru/pattern/decorator) have very similar class structures. Both patterns rely on recursive composition to pass the execution through a series of objects. However, there are several crucial differences. The _CoR_ handlers can execute arbitrary operations independently of each other. They can also stop passing the request further at any point. On the other hand, various _Decorators_ can extend the object’s behavior while keeping it consistent with the base interface. In addition, decorators aren’t allowed to break the flow of the request.
0
Use the Command pattern when you want to queue operations, schedule their execution, or execute them remotely.
0
How to Implement
1
Intent
1
This happens a lot when your code works with objects passed to you from 3rd-party code via some interface. The concrete classes of these objects are unknown, and you couldn’t depend on them even if you wanted to.
0
![Inheritance vs. Aggregation](https://refactoring.guru/images/patterns/diagrams/decorator/solution1-en.png)
0
In our notifications example, let’s leave the simple email notification behavior inside the base `Notifier` class, but turn all other notification methods into decorators.
0
The bigger the code grew, the messier it became.
0
![Reverting operations in the editor](https://refactoring.guru/images/patterns/diagrams/memento/problem1-en.png)
0
But it can also happen when working with extremely sloppy code. Whatever you improve, the code as a whole remains a disaster.
0
You often experience this need when dealing with large, resource-intensive objects such as database connections, file systems, and network resources.
0
The division of a cell.
0
To be able to revert operations, you need to implement the history of performed operations. The command history is a stack that contains all executed command objects along with related backups of the application’s state.
0
As long as all product classes implement a common interface, you can pass their objects to the client code without breaking it.
0
Business pressure
1
The GUI objects delegate the work to commands.
0
At first glance, this change may look pointless: we just moved the constructor call from one part of the program to another. However, consider this: now you can override the factory method in a subclass and change the class of products being created by the method.
0
- Many designs start by using [Factory Method](https://refactoring.guru/pattern/factory-method) (less complicated and more customizable via subclasses) and evolve toward [Abstract Factory](https://refactoring.guru/pattern/abstract-factory), [Prototype](https://refactoring.guru/pattern/prototype), or [Builder](https://refactoring.guru/pattern/builder) (more flexible, but more complicated). - [Builder](https://refactoring.guru/pattern/builder) focuses on constructing complex objects step by step. [Abstract Factory](https://refactoring.guru/pattern/abstract-factory) specializes in creating families of related objects. _Abstract Factory_ returns the product immediately, whereas _Builder_ lets you run some additional construction steps before fetching the product. - [Abstract Factory](https://refactoring.guru/pattern/abstract-factory) classes are often based on a set of [Factory Methods](https://refactoring.guru/pattern/factory-method), but you can also use [Prototype](https://refactoring.guru/pattern/prototype) to compose the methods on these classes. - [Abstract Factory](https://refactoring.guru/pattern/abstract-factory) can serve as an alternative to [Facade](https://refactoring.guru/pattern/facade) when you only want to hide the way the subsystem objects are created from the client code. - You can use [Abstract Factory](https://refactoring.guru/pattern/abstract-factory) along with [Bridge](https://refactoring.guru/design-patterns/bridge). This pairing is useful when some abstractions defined by _Bridge_ can only work with specific implementations. In this case, _Abstract Factory_ can encapsulate these relations and hide the complexity from the client code. - [Abstract Factories](https://refactoring.guru/pattern/abstract-factory), [Builders](https://refactoring.guru/pattern/builder) and [Prototypes](https://refactoring.guru/pattern/prototype) can all be implemented as [Singletons](https://refactoring.guru/pattern/singleton).
0
Problem
1
In this example, the **Observer** pattern lets the text editor object notify other service objects about changes in its state.
0
Relations with Other Patterns
1
Accessing the business logic layer via a command.
0
Various types of collections.
0
Now, how about the product variants? For each variant of a product family, we create a separate factory class based on the `AbstractFactory` interface. A factory is a class that returns products of a particular kind. For example, the `ModernFurnitureFactory` can only create `ModernChair`, `ModernSofa` and `ModernCoffeeTable` objects.
0
Solution
1
- The code may become more complicated than it should be, since a lot of new interfaces and classes are introduced along with the pattern.
0
Pseudocode
1
You could try the direct approach: unwrap all the boxes, go over all the products and then calculate the total. That would be doable in the real world; but in a program, it’s not as simple as running a loop. You have to know the classes of `Products` and `Boxes` you’re going through, the nesting level of the boxes and other nasty details beforehand. All of this makes the direct approach either too awkward or even impossible.
0
The Prototype pattern provides the client code with a general interface for working with all objects that support cloning. This interface makes the client code independent from the concrete classes of objects that it clones.
0
A subscription mechanism lets individual objects subscribe to event notifications.
0
Problem
1
Pseudocode
1
Second, the state backups may consume quite a lot of RAM. Therefore, sometimes you can resort to an alternative implementation: instead of restoring the past state, the command performs the inverse operation. The reverse operation also has a price: it may turn out to be hard or even impossible to implement.
0
Real apps might have dozens of different subscriber classes that are interested in tracking events of the same publisher class. You wouldn’t want to couple the publisher to all of those classes. Besides, you might not even know about some of them beforehand if your publisher class is supposed to be used by other people.
0
Use the Factory Method when you want to save system resources by reusing existing objects instead of rebuilding them each time.
0
Solution
1
![The Adapter pattern example](https://refactoring.guru/images/patterns/content/adapter/adapter-comic-1-en.png)
0
An analogy to an algorithm is a cooking recipe: both have clear steps to achieve a goal. On the other hand, a pattern is more like a blueprint: you can see what the result and its features are, but the exact order of implementation is up to you.
0
Relations with Other Patterns
1
Product families and their variants.
0
Applicability
1
The Builder pattern suggests that you extract the object construction code out of its own class and move it to separate objects called _builders_.
0
The pattern extracts the repeating intrinsic state from a main `Tree` class and moves it into the flyweight class `TreeType`.
0
Great news, right? But how about the code? At present, most of your code is coupled to the `Truck` class. Adding `Ships` into the app would require making changes to the entire codebase. Moreover, if later you decide to add another type of transportation to the app, you will probably need to make all of these changes again.
0
The Factory Method pattern suggests that you replace direct object construction calls (using the `new` operator) with calls to a special _factory_ method. Don’t worry: the objects are still created via the `new` operator, but it’s being called from within the factory method. Objects returned by a factory method are often referred to as _products._
0
A Modern-style sofa doesn’t match Victorian-style chairs.
0
The Decorator lets you structure your business logic into layers, create a decorator for each layer and compose objects with various combinations of this logic at runtime. The client code can treat all these objects in the same way, since they all follow a common interface.
0
- Refactoring helps you understand other people’s code. If you have to deal with someone else’s dirty code, try to refactor it first. Clean code is much easier to grasp. You will improve it not only for yourself but also for those who use it after you. - Refactoring makes it easier to add new features. It’s much easier to make changes in clean code.
0
Problem
1
- Applying the pattern can be overkill if a state machine has only a few states or rarely changes.
0
- **Creational patterns** provide object creation mechanisms that increase flexibility and reuse of existing code. - **Structural patterns** explain how to assemble objects and classes into larger structures, while keeping these structures flexible and efficient. - **Behavioral patterns** take care of effective communication and the assignment of responsibilities between objects.
0
Structure
1
The application wraps the data source object with a pair of decorators. Both wrappers change the way the data is written to and read from the disk:
0
Pros and Cons
1
In this example, the **Iterator** pattern is used to walk through a special kind of collection which encapsulates access to Facebook’s social graph. The collection provides several iterators that can traverse profiles in various ways.
0
The Abstract Factory interface declares a set of creation methods that the client code can use to produce different types of UI elements. Concrete factories correspond to specific operating systems and create the UI elements that match that particular OS.
0
The Command pattern can turn a specific method call into a stand-alone object. This change opens up a lot of interesting uses: you can pass commands as method arguments, store them inside other objects, switch linked commands at runtime, etc.
0
It looks like we’ve got a conflict. Either the customer wastes time checking product availability or the store wastes resources notifying the wrong customers.
0
- You can extend an object’s behavior without making a new subclass. - You can add or remove responsibilities from an object at runtime. - You can combine several behaviors by wrapping an object into multiple decorators. - _Single Responsibility Principle_. You can divide a monolithic class that implements many possible variants of behavior into several smaller classes.
0
As with any other object, a command can be serialized, which means converting it to a string that can be easily written to a file or a database. Later, the string can be restored as the initial command object. Thus, you can delay and schedule command execution. But there’s even more! In the same way, you can queue, log or send commands over the network.
0
Number of class combinations grows in geometric progression.
0
Solution
1
- You can use [Builder](https://refactoring.guru/pattern/builder) when creating complex [Composite](https://refactoring.guru/pattern/composite) trees because you can program its construction steps to work recursively. - [Chain of Responsibility](https://refactoring.guru/pattern/chain-of-responsibility) is often used in conjunction with [Composite](https://refactoring.guru/pattern/composite). In this case, when a leaf component gets a request, it may pass it through the chain of all of the parent components down to the root of the object tree. - You can use [Iterators](https://refactoring.guru/pattern/iterator) to traverse [Composite](https://refactoring.guru/pattern/composite) trees. - You can use [Visitor](https://refactoring.guru/pattern/visitor) to execute an operation over an entire [Composite](https://refactoring.guru/pattern/composite) tree. - You can implement shared leaf nodes of the [Composite](https://refactoring.guru/pattern/composite) tree as [Flyweights](https://refactoring.guru/pattern/flyweight) to save some RAM. - [Composite](https://refactoring.guru/pattern/composite) and [Decorator](https://refactoring.guru/pattern/decorator) have similar structure diagrams since both rely on recursive composition to organize an open-ended number of objects. A _Decorator_ is like a _Composite_ but only has one child component. There’s another significant difference: _Decorator_ adds additional responsibilities to the wrapped object, while _Composite_ just “sums up” its children’s results. However, the patterns can also cooperate: you can use _Decorator_ to extend the behavior of a specific object in the _Composite_ tree. - Designs that make heavy use of [Composite](https://refactoring.guru/pattern/composite) and [Decorator](https://refactoring.guru/pattern/decorator) can often benefit from using [Prototype](https://refactoring.guru/pattern/prototype). Applying the pattern lets you clone complex structures instead of re-constructing them from scratch.
0
Imagine that you’re creating a text editor app. In addition to simple text editing, your editor can format text, insert inline images, etc.
0
This constant data of an object is usually called the _intrinsic state_. It lives within the object; other objects can only read it, not change it. The rest of the object’s state, often altered “from the outside” by other objects, is called the _extrinsic state_.
0
**Factory Method** is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
0
The Builder pattern lets you construct products step-by-step. You could defer execution of some steps without breaking the final product. You can even call steps recursively, which comes in handy when you need to build an object tree.
0
There’s a slight limitation though: subclasses may return different types of products only if these products have a common base class or interface. Also, the factory method in the base class should have its return type declared as this interface.
0
Lazy initialization (virtual proxy). This is when you have a heavyweight service object that wastes system resources by being always up, even though you only need it from time to time.
0
Apps might configure complex stacks of notification decorators.
0
1. **Abstract Products** declare interfaces for a set of distinct but related products which make up a product family. 2. **Concrete Products** are various implementations of abstract products, grouped by variants. Each abstract product (chair/sofa) must be implemented in all given variants (Victorian/Modern). 3. The **Abstract Factory** interface declares a set of methods for creating each of the abstract products. 4. **Concrete Factories** implement creation methods of the abstract factory. Each concrete factory corresponds to a specific variant of products and creates only those product variants. 5. Although concrete factories instantiate concrete products, signatures of their creation methods must return corresponding _abstract_ products. This way the client code that uses a factory doesn’t get coupled to the specific variant of the product it gets from a factory. The **Client** can work with any concrete factory/product variant, as long as it communicates with their objects via abstract interfaces.
0
1. Make sure that you can clearly define the common construction steps for building all available product representations. Otherwise, you won’t be able to proceed with implementing the pattern. 2. Declare these steps in the base builder interface. 3. Create a concrete builder class for each of the product representations and implement their construction steps. Don’t forget about implementing a method for fetching the result of the construction. The reason why this method can’t be declared inside the builder interface is that various builders may construct products that don’t have a common interface. Therefore, you don’t know what would be the return type for such a method. However, if you’re dealing with products from a single hierarchy, the fetching method can be safely added to the base interface. 4. Think about creating a director class. It may encapsulate various ways to construct a product using the same builder object. 5. The client code creates both the builder and the director objects. Before construction starts, the client must pass a builder object to the director. Usually, the client does this only once, via parameters of the director’s class constructor. The director uses the builder object in all further construction. There’s an alternative approach, where the builder is passed to a specific product construction method of the director. 6. The construction result can be obtained directly from the director only if all products follow the same interface. Otherwise, the client should fetch the result from the builder.
0
An example of isolating multiple dependencies within a single facade class.
0
- In `Draft`, it moves the document to moderation. - In `Moderation`, it makes the document public, but only if the current user is an administrator. - In `Published`, it doesn’t do anything at all.
0
Inefficient solutions
1
![Solution with the Proxy pattern](https://refactoring.guru/images/patterns/diagrams/proxy/solution-en.png)
0
As a result, you will end up with pretty nasty code, riddled with conditionals that switch the app’s behavior depending on the class of transportation objects.
0
- Consider implementing the Abstract Factory when you have a class with a set of [Factory Methods](https://refactoring.guru/pattern/factory-method) that blur its primary responsibility. - In a well-designed program _each class is responsible only for one thing_. When a class deals with multiple product types, it may be worth extracting its factory methods into a stand-alone factory class or a full-blown Abstract Factory implementation.
0
- Inheritance is static. You can’t alter the behavior of an existing object at runtime. You can only replace the whole object with another one that’s created from a different subclass. - Subclasses can have just one parent class. In most languages, inheritance doesn’t let a class inherit behaviors of multiple classes at the same time.
0
Using the Composite pattern makes sense only when the core model of your app can be represented as a tree.
0