text
stringlengths 3
2.83k
| label
int64 0
1
|
---|---|
Extending a class is the first thing that comes to mind when you need to alter an object’s behavior. However, inheritance has several serious caveats that you need to be aware of. | 0 |
The object that has some interesting state is often called _subject_, but since it’s also going to notify other objects about the changes to its state, we’ll call it _publisher_. All other objects that want to track changes to the publisher’s state are called _subscribers_. | 0 |
That’s a lot of code! And it must all be put into a single place so that you don’t pollute the program with duplicate code. | 0 |
Note that you can always adjust this limitation and allow creating any number of Singleton instances. The only piece of code that needs changing is the body of the `getInstance` method. | 0 |
If your code has access to the Singleton class, then it’s able to call the Singleton’s static method. So whenever that method is called, the same object is always returned. | 0 |
Relations with Other Patterns | 1 |
New functionality shouldn’t be created during refactoring. | 1 |
Pseudocode | 1 |
Notifying objects about events that happen to other objects. | 0 |
Relations with Other Patterns | 1 |
Visiting the store vs. sending spam | 0 |
Many programming languages have the `final` keyword that can be used to prevent further extension of a class. For a final class, the only way to reuse the existing behavior would be to wrap the class with your own wrapper, using the Decorator pattern. | 0 |
Several classes implement the same functionality. | 0 |
Use the pattern to reduce duplication of the traversal code across your app. | 0 |
In an ideal world, we’d want to put this code directly into our object’s class, but that isn’t always possible. For instance, the class may be part of a closed 3rd-party library. | 0 |
Patterns try to systematize approaches that are already widely used. This unification is viewed by many as a dogma, and they implement patterns “to the letter”, without adapting them to the context of their project. | 0 |
“Wrapper” is the alternative nickname for the Decorator pattern that clearly expresses the main idea of the pattern. A _wrapper_ is an object that can be linked with some _target_ object. The wrapper contains the same set of methods as the target and delegates to it all requests it receives. However, the wrapper may alter the result by doing something either before or after it passes the request to the target. | 0 |
The main purpose of refactoring is to fight technical debt. It transforms a mess into clean code and simple design. | 0 |
Some pattern catalogs list other useful details, such as applicability of the pattern, implementation steps and relations with other patterns. | 0 |
Since you can link the handlers in the chain in any order, all requests will get through the chain exactly as you planned. | 0 |
 | 0 |
Following this approach, we can extract the color-related code into its own class with two subclasses: `Red` and `Blue`. The `Shape` class then gets a reference field pointing to one of the color objects. Now the shape can delegate any color-related work to the linked color object. That reference will act as a bridge between the `Shape` and `Color` classes. From now on, adding new colors won’t require changing the shape hierarchy, and vice versa. | 0 |
There’s one more thing left to clarify: if the client is only exposed to the abstract interfaces, what creates the actual factory objects? Usually, the application creates a concrete factory object at the initialization stage. Just before that, the app must select the factory type depending on the configuration or the environment settings. | 0 |
1. If there’s no pre-existing service interface, create one to make proxy and service objects interchangeable. Extracting the interface from the service class isn’t always possible, because you’d need to change all of the service’s clients to use that interface. Plan B is to make the proxy a subclass of the service class, and this way it’ll inherit the interface of the service.
2. Create the proxy class. It should have a field for storing a reference to the service. Usually, proxies create and manage the whole life cycle of their services. On rare occasions, a service is passed to the proxy via a constructor by the client.
3. Implement the proxy methods according to their purposes. In most cases, after doing some work, the proxy should delegate the work to the service object.
4. Consider introducing a creation method that decides whether the client gets a proxy or a real service. This can be a simple static method in the proxy class or a full-blown factory method.
5. Consider implementing lazy initialization for the service object. | 0 |
Intent | 1 |
- You can work with complex tree structures more conveniently: use polymorphism and recursion to your advantage.
- _Open/Closed Principle_. You can introduce new element types into the app without breaking the existing code, which now works with the object tree. | 0 |
As a result, the business logic of your classes would become tightly coupled to the implementation details of 3rd-party classes, making it hard to comprehend and maintain. | 0 |
- _Single Responsibility Principle_. You can extract the communications between various components into a single place, making it easier to comprehend and maintain.
- _Open/Closed Principle_. You can introduce new mediators without having to change the actual components.
- You can reduce coupling between various components of a program.
- You can reuse individual components more easily. | 0 |
 | 0 |
There are several options where this method could be placed. The most obvious place is a flyweight container. Alternatively, you could create a new factory class. Or you could make the factory method static and put it inside an actual flyweight class. | 0 |
This is when the project resembles a monolith rather than the product of individual modules. In this case, any changes to one part of the project will affect others. Team development is made more difficult because it’s difficult to isolate the work of individual members. | 0 |
An object that supports cloning is called a _prototype_. When your objects have dozens of fields and hundreds of possible configurations, cloning them might serve as an alternative to subclassing. | 0 |
Use the Factory Method when you want to provide users of your library or framework with a way to extend its internal components. | 0 |
The same collection can be traversed in several different ways. | 0 |
1. Add a private static field to the class for storing the singleton instance.
2. Declare a public static creation method for getting the singleton instance.
3. Implement “lazy initialization” inside the static method. It should create a new object on its first call and put it into the static field. The method should always return that instance on all subsequent calls.
4. Make the constructor of the class private. The static method of the class will still be able to call the constructor, but not the other objects.
5. Go over the client code and replace all direct calls to the singleton’s constructor with calls to its static creation method. | 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.
- [Facade](https://refactoring.guru/pattern/facade) and [Mediator](https://refactoring.guru/pattern/mediator) have similar jobs: they try to organize collaboration between lots of tightly coupled classes.
- _Facade_ defines a simplified interface to a subsystem of objects, but it doesn’t introduce any new functionality. The subsystem itself is unaware of the facade. Objects within the subsystem can communicate directly.
- _Mediator_ centralizes communication between components of the system. The components only know about the mediator object and don’t communicate directly.
- The difference between [Mediator](https://refactoring.guru/pattern/mediator) and [Observer](https://refactoring.guru/pattern/observer) is often elusive. In most cases, you can implement either of these patterns; but sometimes you can apply both simultaneously. Let’s see how we can do that.
The primary goal of _Mediator_ is to eliminate mutual dependencies among a set of system components. Instead, these components become dependent on a single mediator object. The goal of _Observer_ is to establish dynamic one-way connections between objects, where some objects act as subordinates of others.
There’s a popular implementation of the _Mediator_ pattern that relies on _Observer_. The mediator object plays the role of publisher, and the components act as subscribers which subscribe to and unsubscribe from the mediator’s events. When _Mediator_ is implemented this way, it may look very similar to _Observer_.
When you’re confused, remember that you can implement the Mediator pattern in other ways. For example, you can permanently link all the components to the same mediator object. This implementation won’t resemble _Observer_ but will still be an instance of the Mediator pattern.
Now imagine a program where all components have become publishers, allowing dynamic connections between each other. There won’t be a centralized mediator object, only a distributed set of observers. | 0 |
Checklist of refactoring done _right way_ | 1 |
All of these options—the random directions born in your head, the smartphone navigator or the human guide—act as iterators over the vast collection of sights and attractions located in Rome. | 0 |
Solution | 1 |
1. The **Client** is a class that contains the existing business logic of the program.
2. The **Client Interface** describes a protocol that other classes must follow to be able to collaborate with the client code.
3. The **Service** is some useful class (usually 3rd-party or legacy). The client can’t use this class directly because it has an incompatible interface.
4. The **Adapter** is a class that’s able to work with both the client and the service: it implements the client interface, while wrapping the service object. The adapter receives calls from the client via the adapter interface and translates them into calls to the wrapped service object in a format it can understand.
5. The client code doesn’t get coupled to the concrete adapter class as long as it works with the adapter via the client interface. Thanks to this, you can introduce new types of adapters into the program without breaking the existing client code. This can be useful when the interface of the service class gets changed or replaced: you can just create a new adapter class without changing the client code. | 0 |
You can create an _adapter_. This is a special object that converts the interface of one object so that another object can understand it. | 0 |
Pseudocode | 1 |
This structure may look similar to the [Strategy](https://refactoring.guru/pattern/strategy) pattern, but there’s one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other. | 0 |
Patterns are often confused with algorithms, because both concepts describe typical solutions to some known problems. While an algorithm always defines a clear set of actions that can achieve some goal, a pattern is a more high-level description of a solution. The code of the same pattern applied to two different programs may be different. | 0 |
 | 0 |
How to Implement | 1 |
 | 0 |
A third alternative is that you could spend some of the trip’s budget and hire a local guide who knows the city like the back of his hand. The guide would be able to tailor the tour to your likings, show you every attraction and tell a lot of exciting stories. That’ll be even more fun; but, alas, more expensive, too. | 0 |
Here’s the best part: a handler can decide not to pass the request further down the chain and effectively stop any further processing. | 0 |
As a result, commands become a convenient middle layer that reduces coupling between the GUI and business logic layers. And that’s only a fraction of the benefits that the Command pattern can offer! | 0 |
 | 0 |
This method has two drawbacks. First, it isn’t that easy to save an application’s state because some of it can be private. This problem can be mitigated with the [Memento](https://refactoring.guru/pattern/memento) pattern. | 0 |
Solution | 1 |
The Factory Method separates product construction code from the code that actually uses the product. Therefore it’s easier to extend the product construction code independently from the rest of the code. | 0 |
Use the Command pattern when you want to parametrize objects with operations. | 0 |
The buttons and switches in your smartphone behave differently depending on the current state of the device: | 0 |
- A [Facade](https://refactoring.guru/pattern/facade) class can often be transformed into a [Singleton](https://refactoring.guru/pattern/singleton) since a single facade object is sufficient in most cases.
- [Flyweight](https://refactoring.guru/pattern/flyweight) would resemble [Singleton](https://refactoring.guru/pattern/singleton) if you somehow managed to reduce all shared states of the objects to just one flyweight object. But there are two fundamental differences between these patterns:
1. There should be only one Singleton instance, whereas a _Flyweight_ class can have multiple instances with different intrinsic states.
2. The _Singleton_ object can be mutable. Flyweight objects are immutable.
- [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 |
It seems like only lazy people haven’t criticized design patterns yet. Let’s take a look at the most typical arguments against using patterns. | 0 |
How to Implement | 1 |
Structure | 1 |
- You can control the service object without clients knowing about it.
- You can manage the lifecycle of the service object when clients don’t care about it.
- The proxy works even if the service object isn’t ready or is not available.
- _Open/Closed Principle_. You can introduce new proxies without changing the service or clients. | 0 |
To achieve this, you create a subclass `UIWithRoundButtons` from a base framework class and override its `createButton` method. While this method returns `Button` objects in the base class, you make your subclass return `RoundButton` objects. Now use the `UIWithRoundButtons` class instead of `UIFramework`. And that’s about it! | 0 |
In most cases most of the parameters will be unused, making [the constructor calls pretty ugly](https://refactoring.guru/smells/long-parameter-list). For instance, only a fraction of houses have swimming pools, so the parameters related to swimming pools will be useless nine times out of ten. | 0 |
 | 0 |
 | 0 |
The simplest solution is to extend the base `House` class and create a set of subclasses to cover all combinations of the parameters. But eventually you’ll end up with a considerable number of subclasses. Any new parameter, such as the porch style, will require growing this hierarchy even more. | 0 |
Use the Facade when you want to structure a subsystem into layers. | 0 |
Lack of tests | 1 |
How to Implement | 1 |
But no matter how a collection is structured, it must provide some way of accessing its elements so that other code can use these elements. There should be a way to go through each element of the collection without accessing the same elements over and over. | 0 |
Adding a new class to the program isn’t that simple if the rest of the code is already coupled to existing classes. | 0 |
In the code it might look like this: a GUI object calls a method of a business logic object, passing it some arguments. This process is usually described as one object sending another a _request_. | 0 |
1. The **Service Interface** declares the interface of the Service. The proxy must follow this interface to be able to disguise itself as a service object.
2. The **Service** is a class that provides some useful business logic.
3. The **Proxy** class has a reference field that points to a service object. After the proxy finishes its processing (e.g., lazy initialization, logging, access control, caching, etc.), it passes the request to the service object.
Usually, proxies manage the full lifecycle of their service objects.
4. The **Client** should work with both services and proxies via the same interface. This way you can pass a proxy into any code that expects a service object. | 0 |
Probably the most obvious and convenient place where this code could be placed is the constructor of the class whose objects we’re trying to reuse. However, a constructor must always return **new objects** by definition. It can’t return existing instances. | 0 |
During a code review | 1 |
This example illustrates how the **Bridge** pattern can help divide the monolithic code of an app that manages devices and their remote controls. The `Device` classes act as the implementation, whereas the `Remote`s act as the abstraction. | 0 |
Pre-built prototypes can be an alternative to subclassing. | 0 |
Also known as: Action, Transaction | 0 |
Dependency Inversion Principle implies that high-level modules should not depend on low-level modules, both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. The dependency inversion principle helps us to couple software modules loosely.
The above line simply state that if a high module or class will be dependent more on low-level modules or class then your code would have tight coupling and if you will try to make a change in one class it can break another class which is risky at the production level. So always try to make classes loosely coupled as much as you can and you can achieve this through abstraction. The main motive of this principle is decoupling the dependencies so if class A changes the class B doesn’t need to care or know about the changes.
You can consider the real-life example of a TV remote battery. Your remote needs a battery but it’s not dependent on the battery brand. You can use any XYZ brand that you want and it will work. So we can say that the TV remote is loosely coupled with the brand name. Dependency Inversion makes your code more reusable. | 0 |
Relations with Other Patterns | 1 |
The Prototype pattern delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning. This interface lets you clone an object without coupling your code to the class of that object. Usually, such an interface contains just a single `clone` method. | 0 |
Logging requests (logging proxy). This is when you want to keep a history of requests to the service object. | 0 |
Nice! But there’s a catch. Not all objects can be copied that way because some of the object’s fields may be private and not visible from outside of the object itself. | 0 |
Structure | 1 |
1. Make all products follow the same interface. This interface should declare methods that make sense in every product.
2. Add an empty factory method inside the creator class. The return type of the method should match the common product interface.
3. In the creator’s code find all references to product constructors. One by one, replace them with calls to the factory method, while extracting the product creation code into the factory method.
You might need to add a temporary parameter to the factory method to control the type of returned product.
At this point, the code of the factory method may look pretty ugly. It may have a large `switch` statement that picks which product class to instantiate. But don’t worry, we’ll fix it soon enough.
4. Now, create a set of creator subclasses for each type of product listed in the factory method. Override the factory method in the subclasses and extract the appropriate bits of construction code from the base method.
5. If there are too many product types and it doesn’t make sense to create subclasses for all of them, you can reuse the control parameter from the base class in subclasses.
For instance, imagine that you have the following hierarchy of classes: the base `Mail` class with a couple of subclasses: `AirMail` and `GroundMail`; the `Transport` classes are `Plane`, `Truck` and `Train`. While the `AirMail` class only uses `Plane` objects, `GroundMail` may work with both `Truck` and `Train` objects. You can create a new subclass (say `TrainMail`) to handle both cases, but there’s another option. The client code can pass an argument to the factory method of the `GroundMail` class to control which product it wants to receive.
6. If, after all of the extractions, the base factory method has become empty, you can make it abstract. If there’s something left, you can make it a default behavior of the method. | 0 |
 | 0 |
Local execution of a remote service (remote proxy). This is when the service object is located on a remote server. | 0 |
Pros and Cons | 1 |
It frequently happens when you move away from refactoring with small changes and mix a whole bunch of refactorings into one big change. So it’s very easy to lose your mind, especially if you have a time limit. | 0 |
Delayed refactoring | 1 |
Saving snapshots of the text editor’s state. | 0 |
**Adapter** is a structural design pattern that allows objects with incompatible interfaces to collaborate. | 0 |
The pattern lets you extract all the relationships between classes into a separate class, isolating any changes to a specific component from the rest of the components. | 0 |
The Adapter pretends to be a round peg, with a radius equal to a half of the square’s diameter (in other words, the radius of the smallest circle that can accommodate the square peg). | 0 |
Possible states and transitions of a document object. | 0 |
Applicability | 1 |
All shape classes follow the same interface, which provides a cloning method. A subclass may call the parent’s cloning method before copying its own field values to the resulting object. | 0 |
Imagine that you’re working on an online ordering system. You want to restrict access to the system so only authenticated users can create orders. Also, users who have administrative permissions must have full access to all orders. | 0 |
 | 0 |
We could apply the same approach to other behaviors such as formatting messages or composing the recipient list. The client can decorate the object with any custom decorators, as long as they follow the same interface as the others. | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.