Design-Pattern | Design pattern C # version , there are a series | Architecture library
kandi X-RAY | Design-Pattern Summary
kandi X-RAY | Design-Pattern Summary
Design pattern C# version (.NET 6), there are a series of articles to explain
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of Design-Pattern
Design-Pattern Key Features
Design-Pattern Examples and Code Snippets
public class Person {
private final String name;
private final Integer age;
// getters
}
private Person(String name, Integer age) {
this.name = name;
this.age = age;
}
static class Builder {
String name;
Integer age;
Community Discussions
Trending Discussions on Design-Pattern
QUESTION
This explains the "Bridge" pattern I'm referring to: https://refactoring.guru/design-patterns/bridge
Here's a scenario from the post above:
Say you have a geometric Shape class with a pair of subclasses: Circle and Square. You want to extend this class hierarchy to incorporate colors, so you plan to create Red and Blue shape subclasses. However, since you already have two subclasses, you’ll need to create four class combinations such as BlueCircle and RedSquare.
The problem this scenario presents:
Adding new shape types and colors to the hierarchy will grow it exponentially. For example, to add a triangle shape you’d need to introduce two subclasses, one for each color. And after that, adding a new color would require creating three subclasses, one for each shape type. The further we go, the worse it becomes.
To avoid this problem, we implement the Bridge pattern like so:
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.
I understand the how and why of this implementation.
But what if we need a third hierarchy, e.g. BorderStyle
(where a border style can be Straight
, Wavy
, or ZigZag
?)
I guess we could implement a second Implementor class for BorderStyle
and pass it into a Shape
constructor like so:
ANSWER
Answered 2021-Jun-10 at 00:45Yes, this works. There's nothing wrong with adding two Bridge relationships to one abstraction (beyond the complexity of juggling three different hierarchies).
Decorator would certainly not work for this purpose, because it maintains a single hierarchy, which is known to the client. The Implementor
hierarchy in a Bridge (or hierarchies in this case) are unknown to the client.
I would make a clarification to the linked article, where it says,
You want to extend this [shape] class hierarchy to incorporate colors
I think this oversimplifies the motivation for a Bridge. The Implementor
s are not just some attributes you choose to add to your Abstraction
to enhance it. Your Abstraction
requires an Implementor
in order to function at all. The method implementations within subclasses of Abstraction
generally do little except call methods of the Implementor
.
The Abstraction
represents your high-level, business API, while the Implementor
represents a lower-level, primitive API. They are both abstractions, but at different levels. I don't think this is conveyed adequately by shape & color examples because shape and color seem like abstractions at the same level. Both shape and color would be known to the clients, and neither one strictly depends on the other.
So a Bridge is applied for more specific reasons than the given example, but you certainly can have two.
QUESTION
I am trying to organise my code into a more OOP style with each class taking on its own header and cpp file. This is my tree in the package folder in the workspace
...ANSWER
Answered 2021-Jun-09 at 02:37In essence you don't need to include either header into the other. This fixes the circular includes.
In ROS_Topic_Thread.h, friend class Master_Thread;
already forward declares Mater_Thread, so you don't need the Master_Thread.h header.
In Master_Thread.h, you can also forward declare class ROS_Topic_Thread;
before the declaration of the Master_Thread class, since you only use references to ROS_Topic_Thread in the transfer_to_master_buffer
method.
QUESTION
I'm trying to learn the design pattern norme (like refacturing guru), and i have some problem to understand how i could merge the idea of bad design with public getter/setter and factory/Builder that need "out of constructor" variable setter.
for example with the answer of this article to article to Design pattern
As you can understand, each object will need a lot of informations, and adding part should set the needed informations, but to be able to do it, it need accessor to my variable outside the constructor.
Help me figure out what i'm missing.
--- Edit To be more precise, Let's say i have 2 class : CombatObject <---- Spaceships And i have a factory that will create different type of spaceships (principally because i don't want to create more than 10 class just to change the stats of the objects)
in this case, getter/setter are not a bad design (or are they?)
...ANSWER
Answered 2021-May-14 at 17:49Ok i think the comments are right, the way i see the solution is the following :
No Setter, the only way to interact with the object will be with function with a purpose. For exemple, modify HP, add a DoDamage function that will return false if the ship is destoyed and will internally modify the hp (and maybe the damage too, etc..)
Getter can be public, but of course, only "const &"
Clone method is a good idea for future development (prototype pattern)
QUESTION
Some programmers believe Singleton is an anti-pattern
I believe singleton is a design-pattern, but some articles and programmers disagree.
Why? with reason
...ANSWER
Answered 2021-Apr-30 at 09:04As far as I know, the book AntiPatterns by Brown et al, 1998 may have been the first to popularise the term. It defines an anti-pattern like this:
"An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences."
I think that it's worthwhile to pay attention to the phrase decidedly negative consequences. Most solutions come with some disadvantages, but in order for a 'solution' to be an anti-pattern, the disadvantages must clearly outweigh any advantages produced.
I usually look at it another way. If I can solve the problem in a different way that generates at least as many advantages, but fewer disadvantages, then the first 'solution' might be an anti-pattern.
As described in the GoF book, the Singleton design pattern addresses a particular problem: Sometimes you want to ensure that only one instance of a class can exist.
This can be appropriate for performance reasons. If the object holds a large amount of data, making sure that only one exists could improve performance.
Even if the object doesn't hold a large amount of memory, you may want to make a small immutable object a Singleton if you otherwise expect that client code might instantiate millions of identical objects.
Particularly when the Singleton object represents immutable data it's hard to argue that it has decidedly negative consequences. It's basically just a constant, like string.Empty
. The Singleton pattern is a good solution to that kind of problem.
On the other hand, many people use mutable Singletons as a replacement for techniques like Dependency Injection or partial function application. When used in this way, a Singleton becomes a global variable, which most people nowadays agree should be avoided.
Since Singleton has valid uses, I don't think it can be called an anti-pattern. On the other hand, I'd consider a mutable Singleton a code smell bordering on anti-pattern.
QUESTION
These days I am researching the Microservice inter-service communication patterns. So during my research, I found that there are two patterns called SAGA and event sourcing. But I couldn't find a resource on the internet to learn the difference between the two patterns. I mean I know event sourcing will capture the history of the event with the aid of an event store. So as per my understandings, I feel that event sourcing is like an extended version of choreography-based SAGA pattern. So I need to clarify is my argument acceptable or not. I will attach sample diagrams of the two patterns which I found on the internet below. Please use those diagrams during any of your explanations.
...ANSWER
Answered 2021-Apr-02 at 13:08The two are compatible patterns that address different problems, Sagas handle workflow processes where as event sourcing addresses how state is stored. Sagas provide a mechanism for handling a multi-step process and rolling back should steps fail (like a workflow). Where as Event Sourcing is the process of encoding the state of an entity by recording all its past changes.
SagasLets say we are booking a holiday, we need to book flights, a hotel and hire a car. each of these processes is handled by a different microservice.
We could create a microservice named BookingSaga which would be responsible for keeping track of the state of each booking. When we make a booking the BookingSaga service would
- book the hotel
- book the flight
- book the car
these can reply in any order, but if any one fails the BookingSaga would then begin a rollback and cancel any that had already been booked.
https://microservices.io/patterns/data/saga.html
Event SourcingEvent sourcing keeps track of the state of some entity by recording the changes that have happened to it.
- Object A Name changed to "dave"
- Object A Age Changed to 3
- Object A Named changed to "sue"
So we can see that Object A has a name of "sue" and an Age of 3 at the end of all the events. https://microservices.io/patterns/data/event-sourcing.html
QUESTION
I have read an interesting article that suggests to use a custom usechildProps hook to directly write dynamic elements in the parent rather than sending props. The article is here: https://medium.com/the-guild/the-coolest-most-underrated-design-pattern-in-react-cd6210956203
Basically, instead of writing:
...ANSWER
Answered 2021-Apr-02 at 00:23As the error says, you are trying to use an object as a react component (childProp.title
, and childProp.content
). It seems you want to use their children as "content".
QUESTION
I'm having problem understanding the usefulness of Rust enums after reading The Rust Programming Language.
In section 17.3, Implementing an Object-Oriented Design Pattern, we have this paragraph:
If we were to create an alternative implementation that didn’t use the state pattern, we might instead use
match
expressions in the methods onPost
or even in themain
code that checks the state of the post and changes behavior in those places. That would mean we would have to look in several places to understand all the implications of a post being in the published state! This would only increase the more states we added: each of thosematch
expressions would need another arm.
I agree completely. It would be very bad to use enums in this case because of the reasons outlined. Yet, using enums was my first thought of a more idiomatic implementation. Later in the same section, the book introduces the concept of encoding the state of the objects using types, via variable shadowing.
It's my understanding that Rust enums can contain complex data structures, and different variants of the same enum
can contain different types.
What is a real life example of a design in which enums are the better option? I can only find fake or very simple examples in other sources.
I understand that Rust uses enums for things like Result
and Option
, but those are very simple uses. I was thinking of some functionality with a more complex behavior.
This turned out to be a somewhat open ended question, but I could not find a useful response after searching Google. I'm free to change this question to a more closed version if someone could be so kind as to help me rephrase it.
...ANSWER
Answered 2021-Mar-30 at 04:46A fundamental trade-off between these choices in a broad sense has a name: "the expression problem". You should find plenty on Google under that name, both in general and in the context of Rust.
In the context of the question, the "problem" is to write the code in such a way that both adding a new state and adding a new operation on states does not involve modifying existing implementations.
When using a trait object, it is easy to add a state, but not an operation. To add a state, one defines a new type and implements the trait. To add an operation, naively, one adds a method to the trait but has to intrusively update the trait implementations for all states.
When using an enum for state, it is easy to add a new operation, but not a new state. To add an operation, one defines a new function. To add a new state, naively, one must intrusively modify all the existing operations to handle the new state.
If I explained this well enough, hopefully it should be clear that both will have a place. They are in a way dual to one another.
With this lens, an enum would be a better fit when the operations on the enum are expected to change more than the alternatives. For example, suppose you were trying to represent an abstract syntax tree for C++, which changes every three years. The set of types of AST nodes may not change frequently relative to the set of operations you may want to perform on AST nodes.
With that said, there are solutions to the more difficult options in both cases, but they remain somewhat more difficult. And what code must be modified may not be the primary concern.
QUESTION
I was reading a blog related Repository Pattern. I saw use of withBlogs method.
...ANSWER
Answered 2021-Mar-29 at 16:04It is used for passing data into views. The with
method returns an instance of the view object so that you can continue chaining methods before returning the view. All of the syntax below archives the same thing:
QUESTION
Following is stretagy design pattern example take from here. First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
...ANSWER
Answered 2021-Mar-23 at 07:03The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();
)
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?We need the interface PaymentStrategy
because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
QUESTION
We can undo an action using Command or Memento pattern.
If we are using kafka then we can replay the stream in reverse order to go back to the previous state.
For example, Google docs/sheet etc. also has version history.
in case of pcpartpicker, it looks like the following:
For being safe, I want to commit everything but want to go back to the previous state if needed.
I know we can disable auto-commit and use Transaction Control Language (COMMIT, ROLLBACK, SAVEPOINT). But I am talking about undoing even after I have commited the change.
How can I do That?
...ANSWER
Answered 2021-Mar-22 at 09:19There isn't a real generic answer to this question. It all depends on the structure of your database, span of the transactions across entities, distributed transactions, how much time/transactions are allowed to pass before your can revert the change, etc.
Memento like patternMemento Pattern
is one of the possible approaches, however it needs to be modified due to the nature of the relational databases as follows:
- You need to have
transaction log
table/list that will hold the information of the entities and attributes (tables and columns) that ware affected by the transaction with their primary key, the old and new values (values before the transaction had occurred, and values after the transaction) as well as datetimestamp. This is same with thecommand
(memento
) pattern. - Next you need a mechanism to identify the non-explicit updates that ware triggered by the stored procedures in the database as a consequence of the transaction. This is important, since a change in a table can trigger changes in other tables which ware not explicitly captured by the
command
. - Mechanism for rollback will need to determine if the transaction is eligible for roll-back by building a list of subsequent transactions on the same entities and determine if this transaction is eligible for roll-back, or some subsequent transaction would need to be rolled-back as well before this transaction can be rolled-back.
- In case of a roll-back is allowed after longer period of time, or a
near-realtime
consumption of the data, there should also be alist of transaction observers
, processes that need to be informed that the transaction is no longer valid since they already read the new data and took a decision based on it. Example would be a process generating a cumulative report. When transaction is rolled-back, the rollback will invalidate the report, so the report needs to be generated again.
For a short term roll-back, mainly used for distributed transactions, you can check the Microservices Saga Pattern, and use it as a starting point to build your solution.
History tablesAnother approach is to keep incremental updates
or also known as history tables
. Where each update of the row will be an insert in the history table with new version. Similar to previous case, you need to decide how far back you can go in the history when you try to rollback the committed transaction.
Finally, when you work with business data such as invoice
, inventory
, etc. you also need to check what are the regulations related with the cancelation of committed transactions. As example, in the accounting systems, it's not allowed to delete data, rather a new row with the compensation is added (ex. removing product from shipment list will not delete the product, but add a row with -quantity
to cancel the effect of the original row and keep audit track of the change at the same time.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install Design-Pattern
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page