Where to write the common logic in Java Strategy design pattern? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
This is related to Java Strategy design pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.
I have common code logic to be executed for all the strategies which is have implemented using Java Strategy design pattern. Which is the right place to write this common logics(something like validations and other stuffs).
Consider the below code. Here I want to do file validation which is common across any file type . Something like , the file should exist and its size should be greater than zero and file name validation. All these file related common stuff I want to keep in some place. Which could be a right design for this?
//BaseFileParser.java
public abstract class BaseFileParser{
public abstract void parseFile();
}
//XMLFileParser.java
public class XMLFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing an XML file goes here
}
}
//CSVFileParser.java
public class CSVFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing a CSV file goes here
}
}
//Client.java
public class Client{
private BaseFileParser baseFileParser;
public Client(BaseFileParser baseFileParser){
this.baseFileParser=baseFileParser;
}
public void parseFile(){
baseFileParser.parseFile();
}
public static void main(String args[]){
//Lets say the client needs to parse an XML file
//The file type(XML/CSV) can also be taken as
//input from command line args[]
Client client=new Client(new XMLFileParser());
client.parseFile();
}
}

If you have common behaviour, then abstract class or class is what we can use. So basic idea is to put common logic into some base common strategy class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete strategy.
I am sorry, I am not Java guy, but I've provided comments how it can be implemented in Java. Let me show an example via C#.
This is our abstract class which has common strategy:
public abstract class BaseStrategy
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{ }
public abstract void
UnCommonBehaviourHereShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
UPDATE:
This is your abstract class:
public abstract class BaseFileParser
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public bool IsValid()
{
return true;
}
public abstract void ParseFile();
}
and its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}

Related

What pattern should be used, strategy?

I do have a service which needs to handle two types of meal.
#Service
class MealService {
private final List<MealStrategy> strategies;
MealService(…) {
this.strategies = strategies;
}
void handle() {
var foo = …;
var bar = …;
strategies.forEach(s -> s.remove(foo, bar));
}
}
There are two strategies, ‘BurgerStrategy’ and ‘PastaStrategy’. Both implements Strategy interface with one method called remove which takes two parameters.
BurgerStrategy class retrieves meals of enum type burger from the database and iterate over them and perform some operations. Similar stuff does the PastaStrategy.
The question is, does it make sense to call it Strategy and implement it this way or not?
Also, how to handle duplications of the code in those two services, let’s say both share the same private methods. Does it make sense to create a Helper class or something?
does it make sense to call it Strategy and implement it this way or not
I think these classes ‘BurgerStrategy’ and ‘PastaStrategy’ have common behaviour. Strategy pattern is used when you want to inject one strategy and use it. However, you are iterating through all behaviors. You did not set behaviour by getting one strategy and stick with it. So, in my honour opinion, I think it is better to avoid Strategy word here.
So strategy pattern would look like this. I am sorry, I am not Java guy. Let me show via C#. But I've provided comments of how code could look in Java.
This is our abstraction of strategy:
public interface ISoundBehaviour
{
void Make();
}
and its concrete implementation:
public class DogSound : ISoundBehaviour // implements in Java
{
public void Make()
{
Console.WriteLine("Woof");
}
}
public class CatSound : ISoundBehaviour
{
public void Make()
{
Console.WriteLine("Meow");
}
}
And then we stick with one behaviour that can also be replaced:
public class Dog
{
ISoundBehaviour _soundBehaviour;
public Dog(ISoundBehaviour soundBehaviour)
{
_soundBehaviour = soundBehaviour;
}
public void Bark()
{
_soundBehaviour.Make();
}
public void SetAnotherSound(ISoundBehaviour anotherSoundBehaviour)
{
_soundBehaviour = anotherSoundBehaviour;
}
}
how to handle duplications of the code in those two services, let’s say both share the same private methods.
You can create one base, abstract class. So basic idea is to put common logic into some base common class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete case. Let me show an example.
An abstract class which has common behaviour:
public abstract class BaseMeal
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{
// put here code that can be shared among subclasses to avoid code duplication
}
public abstract void UnCommonBehaviourShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class BurgerSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class PastaSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}

Should we prefer Composition over Inheritance when we can only use default constructor [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I know the advantages of Composition over Inheritance but in some situation instances of the class are being created by framework using default constructor and we can not define constructor with parameter nor we can set attribute of the object using setter methods. To make this situation clear consider following example:
public class Main {
public static void main(String... str){
TargetFramework.component(Child.class);
}
}
Here the TargetFramework get a class and it will create instance of that class behind the scene using default Constructor.
Imagine I want to implement FramewrokInterface as below:
public interface FrameworkInterface {
void setup();
void doAction(Record record);
void doAnotherAction(Record record, boolean isValid);
}
Now I can implement this interface in two ways considering Inheritance and Composition:
Approach 1: (Mixing and Matching Composition and Inheritance)
public abstract class Parent implements FrameworkInterface {
RecordValidator recordValidator;
#Override
public abstract void setup();
#Override
public void doAction(Record record){
boolean isValid = recordValidator.validate(record);
doAnotherAction(record, isValid);
}
#Override
public void doAnotherAction(Record record, boolean isValid){
}
}
In this Implementation I decided to use composition and I've defined a RecordValidator as bellow:
public interface RecordValidator {
boolean validate(Record record);
}
The problem here is that I can't set RecordValidator in Parent class when creating instance of this class because instances of this class are created by framework using default constructor but I can create this instance in setup method in child Class which extends parent class as below:
public class Child extends Parent {
#Override
public void setup() {
recordValidator = new DefaultRecordValidator();
}
}
The setup method of the FramworkInterface will be called just after instance created by default Constructor so we can use it to initialize our RecordValidator attribute; This is kind of Mixing and Matching Composition and Inheritance together to me because I'm using Composition with Inheritance together. However this approach has its own advantages because I've separated the Concern of validation of record from the Parent class Concerns.
Approach 2: (Just Inheritance)
In this approach I've implemented the FrameworkInterface in the following way:
public abstract class Parent1 implements FrameworkInterface {
#Override
public void setup() {
}
#Override
public void doAction(Record record) {
boolean isValid = validate(record);
doAnotherAction(record, isValid);
}
#Override
public void doAnotherAction(Record record, boolean isValid) {
}
protected abstract boolean validate(Record record);
}
This way instead of using composition and defining RecordValidator I've defined abstract validate method in my Parent1 class so that Child class can use it to implement validation behaviour, so the Child class can be implemented as follow:
public class Child extends Parent1 {
#Override
protected boolean validate(Record record) {
return false;
}
}
My question is:
Which approach is better for this situation and what are the pros and cons of them?
Which approach is better for this situation and what are the pros and cons of them?
I would argue that both of them are suboptimal to a degree where I would look for other solutions.
Looking at the sample code, there is, for example, no possibility to mock the dependencies of Child1 in both situations. You could introduce mock capabilities by implementing setters or special constructors that are only used for testing. The core problem I have with this setup, however, is that you bow to the framework.
I would recommend exploring other possibilities, e.g. do the necessary dependency injection manually, then "register" a finished bean with the framework. This is what Uncle Bob means when he talks about keeping the framework at arm's length.
If we start talking about Java in particular and the framework does not allow any other solution to, e.g., create beans beforehand and registering them with the framework, I would contact the framework maintainers and ask to implement CDI support since this is a standardized way to handle Depencency Injection.
Looking at your example, you take two different approaches, i.e. you redefine the capabilites of Parent. Just as you did with Parent in the inheritance example, you could define abstract boolean validate(); in Parent, delegating the implementation to Child. I would even go a step further and define
public interface class Parent extends FrameworkInterface, RecordValidator {
...
}
(all methods in Parent are either abstract or can be seen as defaults, the field can be removed). Thus, each class implementing this interface implements the methods as it sees fit.

Getting my head around implementations [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an interfaceFileService
And an implementation of it FileServiceBean
I want to be able to process multiple filetypes.
e.g. fileService.processFile(FileDescriptor);
Where, the fileDescriptor is a class e.g.
public class FileDescriptor {
#Column(name = "FILE_TYPE")
protected String fileType;
}
Then I want multiple extensions of the FileServiceBean to process different filetypes. And FileServiceBean would have all the methods common to all filetypes.
e.g.
PhotoProcessingBean extends FileProcessingBean
VideoProcessingBean extends FileProcesingBean
How do I make the interface decide what implementation to use? I am rather new to this and not really quite sure how to ask the question to search google for the answer.
Ideally it would not just accept FileDescriptor. e.g. It could be something else like just File.
fileService.processFile(Object);
Well, in the end you have to put the decision logic somewhere, the only question is where?
I think this is a classic application of the factory-pattern: you create an object (the "factory") which has the sole purpose of deciding which concrete implemenation of a common interface to create for a given case. See https://en.wikipedia.org/wiki/Factory_method_pattern
Along the lines of:
PhotoProcessingBean extends FileProcessingBean {...}
VideoProcessingBean extends FileProcesingBean {...}
class FileProcessingFactory {
public static FileService createFileService(FileDescriptor descriptor) {
switch(descriptor.getFileType()) {
case 'Photo': return new PhotoProcessingBean();
case 'Video': return new VideoProcessingBean();
default: // do some error handling
}
}
}
And using it:
for(FileDescriptor descriptor : /* wherever they come from */) {
FileService processor = FileProcessingFactory.createFileService(descriptor);
processor.processFile(descriptor);
}
Sure enough you can also soften up the interface by accepting objects instead of file descriptors. This depends on the concrete application.
Assuming you have an interface:
public interface IFileService{
void processFile();
}
And the FileProcessingBean class that implements this:
public class FileProcessingBean implements IFileService{
//other code here
#Override
public void processFile(){
//add code for implementation of method
}
}
If you have two other classes that extend FileProcessingBean:
public class PhotoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing PHOTO...");
}
}
public class VideoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing VIDEO...");
}
}
If you would like to use it:
//This is an OOP concept called Polymorphism:
IFileService photoProcess = new PhotoProcessingBean();
IFileService videoProcess = new VideoProcessingBean();
Calling photoProcess.processFile(); and videoProcess.processFile() would yield different the implementations:
photoProcess.processFile();
videoProcess.processFile();
And you'll get the following output:
Processing PHOTO...
Processing VIDEO...
Regarding your point about not just accepting FileDescriptor but also 'something else', my recommendation would be to either know exactly what sort of arguments you are expecting, and then either implementing overriding methods or via an interface. It would not be wise to use Object as a method argument as Object is a superclass from which all objects are descendants of. You would essentially be opening the 'floodgates' and potentially run into runtime errors.

Java subclass methods are not overriding despite explicit use of #Override [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make an abstract algorithm class for informed search with different heuristics. My idea was to have different subclasses overwrite the default heuristic() method, but the dynamic binding seems not to be working when I call the subclasses.
In astar.java:
public interface Astar {
abstract String heuristic();
}
In search.java
public class Search implements Astar {
public String heuristic() { return "default heuristic"; }
}
In EuclidianSearch.java:
public class EuclidianSearch extends Search {
#Override
public String heuristic() { return "Euclidian"; }
}
In ChebyshevSearch.java:
public class ChebyshevSearch extends Search {
#Override
public String heuristic() { return "Chebyshev"; }
}
In main.java:
EuclidianSearch e_search = null; ChebyshevDistance ch_search = null;
Search[] SearchObjects = {e_search, ch_search};
for(Search so : SearchObjects) {
System.out.println(so.heuristic());
}
When run, it displays:
default heuristic
default heuristic
I define the array in terms of Search so I can be flexible: eventually, I want to have five or more different heuristics. Why doesn't the heuristic() method of the subclass override that of the superclass?
You will get NullPointerException for calling so.heuristic() because you don't instance class, use these codes :
EuclidianSearch e_search = new EuclidianSearch();
ChebyshevDistance ch_search = new ChebyshevDistance();
but it is not sufficient to solve you problem, you should implement AStart interface by diffrent classes. don't forget that a class which implement a interface should implement all interface method. otherwise, you should define an abstract class to define only some methods and override remain methods in other classes with extend you previous class.
public class Search implements Astar {
#Override
public String heuristic() { return "default heuristic"; }
}

Java polymorphic methods

In Java i have abstract class named Operation and three its subclasses called OperationActivation, OperationPayment and OperationSendEmail.
ADDED FROM COMMENT: Operation* objects are EJB Entity Beans so I can't have business logic inside them.
No I want to create processor class like this:
public class ProcessOperationService {
public void processOperation(Operation operation) {
out.println("process Operation");
process(operation);
}
public void process(OperationActivation operationActivation) {
out.println("process Activation");
}
public void process(OperationPayment operationPayment) {
out.println("process Payment");
}
public void process(OperationSendEmail operationSendEmail) {
out.println("process OperationSendEmail");
}
}
Processing each operation requires different logic so I want to have three different methods , one for each operation.
Of course this code doesn't compile. Am I missing something or it can't be done that way?
You are mixing up overloading and polymorphic method handling. When you overload methods based on the parameter type, that is static polymorphism. Those methods should be called from code that knows at compile-time what the type is. You could possibly do the following, but it wouldn't be clean object-oriented code:
public class ProcessOperationService {
public void processOperation(Operation operation) {
out.println("process Operation");
if (operation instanceof OperationActivation)
process((OperationActivation)operation);
else if (operation instanceof OperationPayment)
process((OperationPayment)operation);
...
}
public void process(OperationActivation operationActivation) {
out.println("process Activation");
}
...
}
It would be much better to let the automatic run-time polymorphism work, by doing as Brian Agnew suggested, and making process be a method of each Operation subtype itself.
Shouldn't your Operation* objects be doing the work themselves ? So you can write (say)
for (Operation op : ops) {
op.process();
}
You can encapsulate the logic for each particular operation in its own class, and that way everything related to OperationPayment remains in the OperationPayment class. You don't need a Processor class (and so you don't need to modify a Processor class everytime you add an Operation)
There are more complex patterns to enable objects to mediate wrt. what they need to execute, but I'm not sure you need something that complex at this stage.
Assumption: Operation* objects are subclasses of Operation
Unless the processOperation(Operation) method is performing some common functionality, you could just remove it and expose the process(Operation) methods.
The Command Pattern (JavaWorld Explanation) might be useful, but it's tricky to tell exactly what properties you want from your question.
The problem with the code is that any object that matches one of the process(Operation*) methods will also match the process(Operation) method. As there are 2 methods that can be used, the compiler is warning you of an ambiguous situation.
If you really want/need the code above, I would suggest implementing the process(Operation*) methods, and modify the process(Operation) method so it is called processCommon(Operation). Then, the first thing each process(Operation*) does is call processCommon.
Alternatively, you can code exactly as Avi said, using instanceof comparisons.
Neither is ideal, but it will accomplish what you want.
So you have an abstract class called 'Operation' and it has 3 classes extending it. Not sure if this is what you are after but I'd imagine it be designed something like this:
Operation.java
public abstract class Operation {
public abstract void process();
}
OperationActivation.java
public class OperationActivation extends Operation {
public void process() {
//Implement OperationActivation specific logic here
}
}
OperationPayment.java
public class OperationPayment extends Operation {
public void process() {
//Implement OperationPayment specific logic here
}
}
OperationSendEmail.java
public class OperationSendEmail extends Operation {
public void process() {
//Implement OperationSendEmail spepcific logic here
}
}
ProcessOperationService.java
public class ProcessOperationService {
public void processOperation(Operation operation) {
out.println("process Operation");
operation.process();
}
}
Won't the Visitor pattern be of use here ?
The class Operation can declare an "accept" method that takes a Visitor object and the subclasses can have provide the implementation :
public interface IOperationVisitor {
public void visit (OperationActivation visited);
public void visit (OperationPayment visited);
public void visit (OperationSendEmail visited);
}
abstract class Operation {
public void accept(IOperationVisitor visitor)();
}
class OperationActivation extends Operation {
public void accept(IOperationvisitor visitor) {
visitor.visit(this);
}
}
Similarly define "accept" method for classes OperationPayment and OperationSendEmail ..
Now your class can implement the visitor :
public class ProcessOperationService implements IOperationVisitor {
public void processOperation(Operation operation) {
operation.accept(this);
}
public void visit (OperationActivation visited) {
// Operation Activation specific implementation
}
public void visit (OperationPayment visited) {
// OperationPayment specific implementation
}
public void visit ((OperationSendEmail visited) {
// (Operation SendEmail specific implementation
}
}

Categories