• Post Reply Bookmark Topic Watch Topic
  • New Topic

Design Pattern for my code  RSS feed

 
Keith Jones
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I'm sure that to you all this might be a simple issue but I'm pulling what little hair I have left out and can't find a solution. The problem is that I have a swing frame class that HAS-A swing panel abstract class. The reason the panel class is abstract is because there are two subclasses of the panel and the concrete instance of that abstract variable depends on the value of some other unrelated variable. Here's the problem: in the frame class I'm going to have to write something like:

if (myvariable == 1) {
absPanel = new ConcretePanel1();
}
else if (myvariable == 2) {
absPanel = new ConcretePanel2();
}

Question is surely there must be a cleverer way of doing this.
 
Kai Witte
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

when the situation is already given as you describe it, so that depending on that variable that has been set in an unchangeable past panel1 or panel2 has to be used, then there are not many options. An alternative would then be a Map<Integer,JPanel> which would reduce the conditionals, but that wouldn't improve the situation much.

If you can change the point where this variable is set, then you can instead of setting that variable to 1 or 2 set a factory. So instead of myvariable = 1 you would do something like panelFactory = Panel1FactoryCreator.createFactory(); (Factory Method). If you really need this value "1" then you can use an Abstract Factory, so that this panelFactory can both create ints and panels in such a way that they fit to each other.

Kai
 
Keith Jones
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kai,

I don't think I understand. How would I do all this?
 
Nalaka Gamage
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try factory method pattern.

REF:
http://javatouch.googlepages.com/factorymethodpattern2

Cheers,
Nalaka
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A factory just moves the logic you already have into another class with only that responsibility. In some applications that helps avoid duplicating the logic all over the place, but even if you do it just once it moves some details out of your main panel so it can focus on the things it really does well.

The map idea can help you change the factory logic from if-elseif-elseif to something simpler, like:

If you load the map from configuration you can add new panels without touching any of this code. "not changing code" is a very productive activity.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!