Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an example of a class change its behavior? Java interface usage

Easiest to explain with an example.

You have a Troll (a class with existing examples) that has to "do something". It behaves differently according to its Mood. It sleeps if it is GoodMood, it stomps its feet if it is AngryMood. Apparently the Troll can change its Mood (I don't really see how this would be done) and therefore its behavior.

We were told, this had to be done using "interfaces", but I don't see how that could be done. Obviously really easy to do this using a String or Enum (for cleanliness), but apparently interfaces had to be used.

I got my grade, this isn't homework, just want to know how this could be done.

like image 978
user2439998 Avatar asked Dec 05 '25 14:12

user2439998


1 Answers

interface Mood{
   behave();
}

class GoodMood implements Mood{
   behave(){
       // behavior for good mood
   }
}


class AngryMood implements Mood{
   behave(){
       // behavior for angry mood
   }
}

class Troll{

    doSomething(Mood m){
         m.behave()
     }
}

call using

new Troll().doSomething(new AngryMood());
new Troll().doSomething(new GoodMood());

Explanation

you have a common interface Mood with an unimplemnted behave method. for different type of moods you can implement it. So in your Troll class you just need to pass appropriate mood class. according to the mood the doSomething() method will perform the related tasks

Benefits

if you want to add any more mood you do not need to make much changes in the main parts of the code. Just create another class , implement the Mood interface, then use like before

And they call it Strategy Design Pattern

like image 186
stinepike Avatar answered Dec 08 '25 02:12

stinepike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!