I have a program to transfer files from one computer to another which uses 4 different classes A, B, C and D. My program creates an object and uses A and B to check and validate the files to be sent. Now I have to add an additional transfer technique. I guess using strategy pattern would be the best case scenario since we can choose either of the transfer techniques. But I wanted to ask whether or not can we use classes A and B to validate the transfer of files in my strategy also? Does this make it a template design pattern rather than a strategy design pattern?
Asked
Active
Viewed 480 times
0
-
Yes, you can reuse the validation. No, that does not create a Template. The difference between Strategy and Template is composition vs inheritance, respectively. – jaco0646 Jul 09 '20 at 12:53
-
So here what would be the advised pattern? I want my two transfer techniques to be loosely coupled. Should I use inheritance or composition? – Jul 09 '20 at 12:54
-
That is a matter of opinion and context, but you can read more about the difference here: https://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-method-and-the-strategy-patterns. Start without design patterns and solve the problem in whatever way is clean and readable. – jaco0646 Jul 09 '20 at 12:56
1 Answers
0
If your strategies are quite complex and have a common schema (i.e. the validation part) you can have a strategytemplate which does the validation, than every concrete strategy class does the rest:
public interface ITransferFileStrategy {
bool TransferFile(File f);
}
public abstract class TransferFileStrategyTemplate {
public bool TransferFile(File f) {
if (!ValidateFile(f)) return false;
return TransferFileInner(f);
}
protected virtual bool ValidateFile(File f) {
//implement it here
}
protected abstract bool TransferFileInner(File f);
}
public class TransferFileStrategyA {
protected override bool TransferFileInner(File f) { ... }
}
you could even use a nested strategy (IValidationStrategy) in TransferFileStrategyTemplate to handle the validation if you know that there will be different kind of validations.

ddfra
- 2,413
- 14
- 24