I am new in design patterns. I am trying to use decorator design pattern to add new codes and functionalities to my existing app.
Suppose I have a class of App which has two methods "Add" and "Multiply". At some point (run time) the app will require to calculate the average as well. So, I am trying to use decorator design pattern to make this possible.
So far I have :
public class App implements Code{
public int a=2;
public int b=3;
@Override
public int Add(int a, int b) {
int add;
add = a+b;
return add;
}
@Override
public int Multiply(int a, int b) {
int mul;
mul= a*b;
return mul;
}
}
In order to do this I define an interface "Code" like this:
public interface Code {
public int Add (int a, int b);
public int Multiply (int a, int b);
}
and then a decorator abstract class "CodeExtention "
public abstract class CodeExtention implements Code{
protected Code extendedCode;
public CodeExtention(Code extendedCode) {
this.extendedCode = extendedCode;
}
@Override
public int Multiply(int a, int b){
return extendedCode.Multiply(a, b);
}
@Override
public int Add(int a, int b){
return extendedCode.Add(a, b);
}
}
Now I define a concert class "AVG" extended from my abstract class like this :
public class AVG extends CodeExtention{
public AVG(Code extendedCode) {
super(extendedCode);
}
public int AVGcalculator (int a, int b){
return (a+b)/2;
}
@Override
public int Add(int a, int b) {
return super.Add(a, b);
}
@Override
public int Multiply(int a, int b) {
return super.Multiply(a, b);
}
}
Now I expect that my app can calculate the average to do so I have in my main :
public static void main(String[] args) {
Code app = new App();
app = new AVG(app);
}
}
Here I can have :
System.out.println(app.Add(3, 4));
System.out.println(app.Multiply(3, 4));
I still cannot have:
System.out.println(app.AVGcalculator(3, 4));
I don't know what is wrong, or even if I can use this design pattern for my scenario!
Aucun commentaire:
Enregistrer un commentaire