Is this a variation of the decorator pattern or a pattern at all?
Below is a simplified version of code I've written to override a class method (using composition), in this case method name i'm overriding is addbuttons(); The class "Screen" adds buttons to a screen whereas class "SubScreen" adds custom buttons to an instance of Screen. Maybe this is not an example of decorator pattern since I'm overriding functionality instead of extending it ? Is there a better way (using a design pattern ?) to achieve same functionality ?
publi开发者_高级运维c class Driver {
public static void main(String args[]){
AddComponents add1 = new Screen();
add1.addButtons();
Screen newScreen = new Screen();
AddComponents add2 = new SubScreen(newScreen);
add2.addButtons();
}
}
public interface AddComponents {
public void addButtons();
}
public class Screen implements AddComponents{
public void addButtons() {
//Add Buttons to screen class
}
}
public class SubScreen implements AddComponents{
private Screen screen;
public SubScreen(Screen screen){
this.screen = screen;
}
public void addButtons() {
//add different custom buttons to Screen class
}
}
Another possibility would be to call it Proxy. Decorator and Proxy are technically very similar - the difference is - in most cases - not a technical one but based on the intention. Your example is a little bit minimal and therefore it is hard to guess the intention correctly.
Edit
At the detailed level: Screen
and SubScreen
do not share any code. If you start adding methods to both implementations and the common interface AddComponents
you might find
- that you must duplicate code both in
Screen
andSubScreen
(or delegate toScreen
) and - that you must add methods to
AddComponents
which make this interface badly named.
If both screen classes are similar both on the abstract logical level and at the implementation level, then a an class AbstractScreen
with two derived classed would be better. To bring back pattern speak: Use a Factory Method in AbstractScreen
to specialize the behaviour regarding the different buttons.
On your current code there is one strange thing: Why is there a method addButton
defined anyway? Simply add the buttons in the appropriate constructor, since the user has to call addButtons
in any case and the method does not have arguments.
Another point not explained is this: SubScreen
has a reference to Screen
which is not used. Why? Will there be more method in all involved classes Screen
, SubScreen
and AddComponents
? Will each method be a in SubScreen
delegate to Screen
or only half of them?
You see - there are many possibilities we do not know and are not shown in the example code but are very important. I'm sure that your head contains a lot of details saying "This proposed stuff will not work because I want to do this and that one way or the other in the near future." Sadly we cannot get the content of your head into this site without more writing. :-)
精彩评论