0

I'm searching for an elegant and most of all "performance careful" way to use laugh() to call maleLaugh() or femaleLaugh(). There is a way to avoid a check each laugh() call? I'm sure there is a design pattern for this.

public class Person {

    boolean gender;
    public Person(boolean gender){
        this.gender = gender;
    }
    public void laugh(){
        //--based on this.genderI call maleLaugh() or femaleLaugh()
    }
    public void maleLaugh(){
        System.out.println("muhahahaha");
    }
    public void femaleLaugh(){
        System.out.println("hihihihihi");
    }

}
Marcelo Tataje
  • 3,849
  • 1
  • 26
  • 51
alfredopacino
  • 2,979
  • 9
  • 42
  • 68
  • 13
    Make `Person` an `interface`. Define two concrete types. `Male` and `Female`. Both implement `laugh()` (but differently). – Elliott Frisch Aug 07 '16 at 20:58
  • Hint: caring about performance this way is very naive; and not helpful. Create good OO designs, and performance will follow; see here for example: http://stackoverflow.com/questions/11064409/why-to-use-polymorphism – GhostCat Aug 07 '16 at 21:03
  • I'm sorry but charge with 'naiveness' without any clue of the project is kind of arrogant. I'm not learning OOP. I'm on a bigdata project. I'm just a little rusty with java. – alfredopacino Aug 07 '16 at 21:07
  • If you'd really want a design pattern, you could use the strategy pattern. – Arjan Aug 08 '16 at 01:36
  • [Polymorphism](http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading) is the answer. – Janez Kuhar Aug 12 '16 at 21:27
  • Based off your question alone (i.e. ignoring OOP solutions for the time being), could you not just go `if (sex) { maleLaugh(); } else { femaleLaugh(); }`? – Tyler Sebastian Aug 12 '16 at 21:35
  • "I'm not learning OOP." You asked for an elegant and performant solution. That solution is OOP. – Kevin Krumwiede Aug 12 '16 at 21:46

0 Answers0