design-patterns | Design Pattern using Modern Perl
kandi X-RAY | design-patterns Summary
kandi X-RAY | design-patterns Summary
Playing with Design Pattern using Modern Perl. This is not the first time anyone has done it and definitely not the last. It is an honest attempt to show the power of Modern Perl. If you look at the individual implementation, you will appreciate it does not take much to get the job done. To keep it lightweight, I am using Moo for the class definition. An interface generally defines the set of methods that an instance of a class that has that interface could respond to. It defines a set of methods, the class that implements it "repeats" the same methods, but provides definition, so interface looks like skeleton of the class. An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code. A concrete class is a class that has an implementation for all of its methods. They cannot have any unimplemented methods. It can also extend an abstract class or implement an interface as long as it implements all their methods. Mohammad S Anwar, .
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-patterns
design-patterns Key Features
design-patterns Examples and Code Snippets
Community Discussions
Trending Discussions on design-patterns
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
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'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
In the Head First Design Patterns book, the authors describe using an iterator to traverse over composite data structures. They provide some sample code which, when executed, prints out a series of menu items stored within the composite. However, if you try to call the iterator more than once, it no longer works as expected and won't produce any results. The following code appears to be causing the problem:
...ANSWER
Answered 2021-Mar-18 at 13:51As the linked issue says in the comments:
QUESTION
I am a little confused as to why Optimistic Locking is actually safe. If I am checking the version at the time of retrieval with the version at the time of update, it seems like I can still have two requests enter the update block if the OS issues an interrupt and swaps the processes before the commit actually occurs. For example:
...ANSWER
Answered 2021-Mar-03 at 22:15Well... that's the optimistic part. The optimism is that it is safe. If you have to be certain it's safe, then that's not optimistic.
The example you show definitely is susceptible to a race condition. Not only because of thread scheduling, but also due to transaction isolation level.
A simple read in MySQL, in the default transaction isolation level of REPEATABLE READ, will read the data that was committed at the time your transaction started.
Whereas updating data will act on the data that is committed at the time of the update. If some other concurrent session has updated the row in the database in the meantime, and committed it, then your update will "see" the latest committed row, not the row viewed by your get method.
The way to avoid the race condition is to not be optimistic. Instead, force exclusive access to the record. Doveryai, no proveryai.
If you only have one app instance, you might use a critical section for this.
If you have multiple app instances, critical sections cannot coordinate other instances, so you need to coordinate in the database. You can do this by using pessimistic locking. Either read the record using a locking read query, or else you can use MySQL's user-defined locks.
QUESTION
I'm learning Java design patterns by "Patterns in Java", volume 1 by Mark Grand (Factory Method specifically). My point is to highlight difference between closest patterns for myself. There are good answers that clarify the difference between Factory Method and Abstract Factory (Design Patterns: Factory vs Factory method vs Abstract Factory, What is the basic difference between the Factory and Abstract Factory Design Patterns?). But I noticed that most of authors mean some other interpretation of Factory Method compared to one I have read in "Patterns in Java". The interpretation from the answers is closer to Factory Method from GoF book.
GoF interpretation:
To be specific I will describe what in my opinion is a key difference between Grand's and GoF interpretations. The source of polymorphism in GoF interpretation is inheritance: different implementations of Creator
create different types of Product
s. The source of polymorphism in Mark Grand interpretations apparently is "data-driven class determination" (example from book):
ANSWER
Answered 2021-Feb-26 at 21:19Question #1.
- No.
- No.
- Sometimes UML obfuscates a thing more than it clarifies a thing.
Question #2.
- I only see one factory interface in the Grand picture. I don't see a separate interface.
- ?
- Yes. And no.
Question #3. No.
Question #4. No.
I'm not as up on my GoF patterns as I used to be, but I'll take a shot at this. I think you are correct about the difference. The GoF pattern uses inheritance for polymorphism and Grand's example uses conditional logic for polymorphism.
The operational difference is that to add a new type in Grand's example, I would modify the method createImage
:
QUESTION
I am following an example of a book (Node.js design patterns) to implement a LIMITED PARALLEL EXECUTION algorithm in Node.js with Javascript.
First, I write a TaskQueue class that handles all the limiting and execution of the tasks.
...ANSWER
Answered 2021-Feb-07 at 18:05The Zalgo situation the author is referring to would be
QUESTION
I have three validators each sequentially dependent on the previous. I might use all three or only the first two or only the first one. E.g.
- Validator 1: Checks whether user exists
- Validator 2: Checks whether requested order exists in the user's order history
- Validator 3: Checks whether that order has a cancel option
Each validator in this list will throw an error if the previous condition is not met. I'm currently using this pattern:
...ANSWER
Answered 2020-Dec-10 at 15:44I suggest looking into the Chain of Responsibility and the Builder Pattern specific for validation. See here:
- https://medium.com/@aleksanderkolata/java-tips-01-handle-validation-in-an-elegant-manner-using-chain-of-responsibility-design-pattern-ad3dcc22479e
- https://medium.com/henrydchan/input-validation-using-design-patterns-9d7b96f87702
You could also look into usage of the Decorator Pattern:
Is there a way to do this that is both safe and explicit?
But before considering one of the patterns which might of course provide more flexibility but also more complexity consider if your rules might really get extended a lot and will be reused and that many cases. Otherwise it might be a bit of over engineering to go with one of the suggested patterns right away.
Also, you can make a lot explizit by using meaningful function names that explicitly tell the reader of the code what specific use case is being performed. Such a function than acts more like an orchestrator of the required validation steps. So your approach (despite of the bad name someTask()) might already fit your needs.
But this is unsafe because there is nothing stopping me from running validator3() and throwing an error if condition 2 hasn't been met.
You could either have each validate exception throw an exception or introduce guard clauses having the major task return if one of the validations fail.
Another option would be to pass in or register a list of validations with the same interface and loop them through. If you need to check for all validations and collect the results (e.g. error code or messages) for each validation step or throw an exception on the first validation is up to your needs.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install design-patterns
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