I understand the concept of Chain of Responsibility Pattern but maybe I'm wrongly using it.
I have several types of product and I have a controller that controls the interface that is displayed for each of these types of product. The user selects the type of product and each controller is responsible for showing and interacting with the appropriate interface.
For this, I'm using the chain of responsibility pattern which doesn't sound okay I think. What I'm doing is creating a chain of controllers and, as soon as I get the product type request, I just pass it to the chain of controllers and let the appropriate controller implement the request.
But when thinking, the same could have been achieved using a simple factory but with many conditional statements.
What do you think about the use of chain of responsibility in this situation?
As for me this task is defenitely not for chain of responsibility.
Usually in chain of responsibility the order of chain elements matters and here it is not the case.
I would try to do the following.
Create some kind of registry, which contains a map with key for productType and value for controller.
Sample implementation:
class ControllerRegistry
{
//declaration for map and constructor
public void Register(string productType, IProductController controller)
{
_map.Add(productType, controller);
}
public IProductController Find(string productType)
{
return _map[productType];
}
}
And during application startup you should register all you controllers by calling ControllerRegistry.Register method.
You get appropriate controller by calling ControllerRegistry.Find method.
As compared with chain of responsibility you will avoid the performanse hit if number of product types is large.
EDIT
Same task topic Design pattern for handling multiple message types
Related
I have the following class hierarchy for Coupon and Deals platform am developing::
Promotion - abstract
- Coupon
- Sale
- Deal
(Coupon, Sale and Deal inherit from Promotion. Promotion has a string attribute called type and an abstract method that initializes the the type attributes of the subclasses to a string value. For instance the type in coupon gets the value "Coupon" etc...)
For each subclass, I have a DAO and Service classes like CouponDAO, CouponService, etc.
In the front-end users can create Coupon or Sale or a Deal through Angular 2 interface so I decided to have the following controllers:
PromotionController - abstract
- CouponController
- SaleController
- DealController
(CouponController, SaleController, DealController inherit from PromotionController )
The PromotionController will contain all the common CRUD functions common to all subclasses and in the specific controllers I will handle specific operations meant for those classes.
A) The issue am facing now is how to instantiate the correct object coming from the client side. For instance when a user submit a Coupon or a Sale or a Deal how do I instantiate the right object. For instance in the PromotionController I have a function like this::
#RequestMapping(value=CREATE_PROMO, method=RequestMethod.POST)
public ResponseEntity<?> create(#RequestBody Promotion promotion){
promotionService.save(promotion);
return new ResponseEntity<>("", HttpStatus.OK);
}
Promotion which is abstract is the argument of the function. Should I use the factory pattern and the **type** attribute to create the right object?
For instance if the type="Coupon" then I create Coupon object, if it is "Sale" then I create the Sale object
B) Since the controller uses the Services objects it means that I have to declare all the three services objects in the PromotionController. Because after instantiating the right object, I need to call its corresponding service to do the job. In the method above I have promotionService which I think should be replaced with the right service of subclass
C) I am looking for how to handle REST APIs that deals with subclasses in the real world like the situation I have described above
D) I was thinking of making it easy for myself by copying all the CRUD operations to their specific controllers but it seems that will be repetitive code.
I think there is a better way that can be done.
I have also tried if I can find an open source project that deals with this situations but it seems all the projects I found use one class and not inheritance. Their REST/APIs don't handle inheritance situations
In my view, keep your endpoints simple. From a REST API standpoint, create individual or only one controller and use the following patterns after the controller layer. From what I have seen, it is always better to keep REST endpoints away from inheritance/reuse and apply it later after receiving and validating the requests.
To instantiate service/helper layer from controllers, use factory method pattern:
https://en.wikipedia.org/wiki/Factory_method_pattern
Create a PromotionServiceFactory which returns the PromotionService implementation depending upon the promotion type.
In controller, invoke corresponding method of promotion service using the factory. The factories still accept arguments of type Promotion.
#RequestMapping(value=CREATE_COUPON, method=RequestMethod.POST)
public ResponseEntity<?> create(#RequestBody Promotion promotion){
//helper if adding one more helper layer. The factory invocation is then //transferred to the helper layer
PromotionService couponService = promotionServiceFactory.get(PROMOTYPES.COUPON);
couponService.save(promotion);
return new ResponseEntity<>("", HttpStatus.OK);
}
From your questions, it seems like that there are common CRUD/other methods for different promotion types. This is a good candidate of the template pattern in the service layer if some of the steps/sub-tasks are same for every promotion and the others vary. Otherwise, you could just store the common CRUD methods by creating an abstract promotion service.
https://en.wikipedia.org/wiki/Template_method_pattern
Create an abstract promotion service with the primary method and implementations of common CRUD methods. Create individual implementations of other promotion service types with respective varying methods.
I think you can handle this in two ways depending upon the logic.
If you want to keep everything Separate then create a difference endpoints for coupon/deal/sale. That way every endpoint will call its controller and so on.
2) If you think code is same that you can use abstract factory pattern to instantiate the correct service and DAO object.
It all depends on your business requirement, I would prefer the second way if code logic is almost same. One controller per inheritance, so that in future if hierarchy increases you do not need to create multiple classes until required.
to answer you (A), I think you could use requestObject.instanceOf() method, to tell the correct subclass type, then handle with correct handler.
I have a file parser that reads text file line by line and creates a 'Event' object that represent the line.
There are 3 types of 'Event' so I created 4 pojos.
EventTypeA, EventTypeB, EventTypeC, EventTypeD that extend a BaseEvent that I push to an arraylist.
Pojos have nothing in common, as each pojo (event) has different set of fields.
Now I have an event handler that should handle all the events in the list based on the type.
I want the best elegant way to process them. I identified four options:
The obvious approach is via polymorphism, but those are pojos and I
don't want to put any business code there.
The second option is simply to check instanceof and casting
BaseEvent to concrete EventType to, but it's not elegant.
Third option is to add type field (enum) to pojo and then do a
'switch' checks (+ the casting) , but it's also not elegant.
Fourth option would be to create a hashmap, where key would be the
name of the pojo class, and the value will a instance of class with
code that handles it. I don't like that as well.
What can you suggest?
Thanks
There many possible solutions to this problem. However, the constraints you gave discard many of them. I think that the main issue here is trying to avoid to modify existing code each time a new Event type will be developed.
One possible solution is to use a Chain of responsibility on handlers. Define a common interface for handlers:
interface EventHandler {
void handle(BasicEvent event);
}
You will have a concrete handler implementation for each type of Event. Then, collect all the events in a common processor.
class EventProcessor {
private List<EventHandler> handlers;
public EventProcessor(List<EventHandler> handlers) {
this.handlers = handlers;
}
public void process(BasicEvent event) {
handlers.forEach(handler -> handler.handle(event));
}
}
In this way, every event will be processed only by the proper handler. Others handler will discard the event. Each time a new event will be develop, it will be sufficient to develop the relative handler and to add it to the chain.
There are many variant of this pattern. IMHO, this is the simplier one.
EDIT
For sake of completeness, if you can remove the requirement you stated at point
Fourth option would be to create a hashmap, where key would be the name of the pojo class, and the value will a instance of class with code that handles it
me and others (see comments below) think that the best approach should be really to have a dedicated Map for handlers.
class EventProcessor {
private Map<EventType, EventHandler> handlers;
public void process(BasicEvent event) {
handlers
.get(event.getType)
.handle(event);
}
}
The most important fact is that the above map handlers has to be built automatically, perhaps using dependency injection. Doing so, when you will add a new type of event, you can guarantee to not violate the Open Closed Principle of SOLID.
Cheers.
The pattern you want is the "Visitor":
https://sourcemaking.com/design_patterns/visitor
I'm using it in a parser that I'm writing. I have an abstract class "AbstractNode", and a concrete class for each node type in the abstract syntax tree (BinaryOperationNode, AssignStatementNode, etc.). My parser gets a reference to the root node of the tree and then process each node sequentially. The Visitor pattern helps me to avoid writing a massive chain of if instanceof/else if(...).
The drawback is having to update the Visitor interface and each class that implements it each time that a new node type is created.
As it seems you main concern is decoupling the EventTypes from their handler I would recomend a Chain of responsibility.
It manages decoupling by passing the EventType among a chain of potential handlers.
Benfits
Reduced coupling, both handler and event have no explicit knowledge of each other
Ability to have multiple handlers per EventType to separate concerns
Concerns
It is not guaranteed that there will be a handler for the event type. This may be able to be addressed with a NotFound handler.
Can we return any object type to an interceptor from action class methods instead of returning a string, then return a string from the interceptor to identify the required result?
Technically, yes, if you bypass the "invoke" mechanism. Should you? Likely not.
The cleaner, canonical S2 approach would be to expose a property to your interceptor, defined by an interface the action implements. For example, you might call it Revisionable or RevisionAware and expose a pair composed of before and after references.
In your interceptor you'd check for that interface, in pseudocode:
if (action instanceof Revisionable) {
return processRevisionablePair();
}
You might include a method in the interface that handles action- or model-specific revisions that returns an appropriate result, or if it's the same across the application, you could wrap up the functionality in the interceptor and have "modified" and/or "unmodified" results, etc.
Action methods that return something other than a string deviates from framework expectations, leading to multiple ways to handle different actions, multiple ways to test, and so on. Yuck. Keep things consistent, and avoid a layer of documentation and differentiation that isn't really necessary.
Lastly, to return a result based on the action method return value, you need to implement a PreResultListener that will provide the result name. Results have already been rendered after invoke returns as per the docs.
You can return instance of Result interface directly from your action.
I'm working on designing a validator for certain objects (fields of those objects). These objects are enclosed in one, bigger object - container.
Example: Car as a container . Consists of Wheels, Engine, Body.
Lets say i need to validate if wheels have correct diameter, engine has correct capacity, body has certain length etc.
Theoretically I think I should validate everything before construction of a container (car).
What is the best way to achieve this? Do I make an abstract validator class with validate() method and implement it in every enclosed class? What about the container, do I just not include it at all in the validation process? Thanks for help.
I'd suggest you not to put the validation logic inside the classes you're going to validate.
I find it better to keep those classes as mere value objects, and create a parallel hierarchy of validators, roughly one for each entity to be validated. Alternatively, you could also create a single validator that can validate all the entities: however, this solution is less scalable and could bring you to violate the open-closed principle when you have to add a new entity (e.g. you want to deal also with the rear-view mirrors of the car).
Assuming you choose the one entity : one validator approach, the validator of the container will first validate the components inside the container and then validate if they fit together.
Please consider also the possibility of using validator frameworks such as Apache Commons Validator, that can save you from writing boilerplate code. However, since I don't know what kind of complex validation you have to perform, I don't know if it fits your needs.
Furthermore, I don't think you should be worried of validating everything before it is constructed. Just construct it and validate afterwards: then, if it violates the validation rules, you can discard it (i.e. don't persist it anywhere).
piggy backing off of gd1 answer, I agree. One such way would be to have a ValidatorAdapter for each of your value objects. So it would look like this:
public class GreenCarValidator {
public GreenCarValidator(Car car) {
// save reference
}
#Override
public boolean isValid() {
return car.getColor().equals("green");
}
}
public class RedCarValidator {
public RedCarValidator(Car car) {
// save reference
}
#Override
public boolean isValid() {
// you could compose more validators here for each property in the car object as needed
return car.getColor().equals("red");
}
}
Now you can have many types of validators for a single type of object, dynamic and configurable at runtime. Should you put the "valid()" method inside the classes the classes as gd1 suggest you not do, you would lose this flexibility.
You could create a ValidatablePart interface with a validate method, have all parts implement this interface, and then have the container validate all inclosed parts as they are being added to the container or perhaps when calling the the container's build or whatever method that is supposed to construct it.
Your Container class could follow the Template Method Design Pattern.
I am working on my struts2 application to solve Parameter tampering problem. I heard this can be solved by implementing ParameterNameAware interface in my actions, but I haven't find a best example explaining this condition. Can anyone provide me a good example on how to use ParameterNameAware. Quick answers will be really appreciated.
The wholde idea about this interface is to maintain a list of valid parameter names and there by rejecting any request parameters that are not in this list(whitelist).This is really helpfull in situations where a hacker tries to include unwanted form field values as a hidden variable that are likely to execute in certain situations.For example, include so many form fiels varialbles (>10000 etc) that may create Denial Of serice on server side.
Once you have implemented this, you can immediatly reject any unwanted parameters in the current request scope or you can take a better control of this situation.
Probable implementation :
Implement the ParameterNameAware interface and override its acceptableParameterName method as follows:
public boolean acceptableParameterName(String parameterName) {
boolean allowedParameterName = true ;
if ( parameterName.contains("session") || parameterName.contains("request") ) {
allowedParameterName = false ;
}
return allowedParameterName;
}
You need to implement this interface in your form bean that is having getter and setter methods in it. In this particular example, if the current request contains any form field variable like request or session, then it is a failure scenario.This is just a typical example here. There is a complete documentation in this link
Class ParametersInterceptor