0

Is there a Design pattern which returns me child or parent class based on condition.

The scenario is:

I have a basic class and a complex class which extends the basic class. What I need is as per user requirement I return basic or complex class. I was able to implement is using basic if else condition but feels that this doesn't seem right logic. There must be a proper way of doing this given a scenario that my classes can have structure like this

public class SimpleClass {}

public class ComplexClass extends SimpleClass {}

public class MoreComplexClass extends ComplexClass {}

and goes on ......

If my question is wrong and if I should be changing the way I'm creating the classes. Please guide.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Use the Factory Pattern to return the run time object dynamically. http://en.wikipedia.org/wiki/Factory_method_pattern – Phani Jul 23 '13 at 19:08
  • Your question doesn't really make sense. Under what conditions do you want to return one vs the other? – bengoesboom Jul 23 '13 at 19:08
  • An interesting read as to why you would NOT want the behaviour you are asking, is the following: http://stackoverflow.com/questions/586363/why-is-super-super-method-not-allowed-in-java , more precisely the first answer – skiwi Jul 23 '13 at 19:09
  • This can be achieved using a Factory Method pattern. Note that most design patterns are not bounded to the programming language. – Luiggi Mendoza Jul 23 '13 at 19:09
  • Requirement here is, I need to present users with different forms as per their input. So if they ask for a simple form I present them the simple one. If they need the complex form (it will contain more attributes than simple one), I'll present them the complex form. So it's like the form is configurable by user. They only fill in what they want – Sandeep Choudhary Jul 28 '13 at 07:30

3 Answers3

2

I think you should better use Factory method pattern instead of Abstract Factory. Look e.g. here http://www.codeproject.com/Articles/37547/Exploring-Factory-Pattern

Oleksandr Karaberov
  • 12,573
  • 10
  • 43
  • 70
1

What you're describing sounds like the Factory method pattern. See a Java example implementation at http://en.wikipedia.org/wiki/Factory_method_pattern#Java_3

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

Such tasks usually implemented by using Factory Method pattern. In you case it can be something like:

public class SimpleClass{
    public static SimpleClass getMyClass(String cond1/*you conditions as parameters here*/){
      if ("case1".equals(cond1))
          return new ComplexClass();
      //...
      return new SimpleClass();
    }
}
antonv
  • 1,227
  • 13
  • 21