Java Reference
In-Depth Information
The main advantage of this solution is that it requires only one class, and thus
it is very compact. On the other hand, adding a new behaviour requires modifica-
tion in several points of the class: a new constant and a new case in the switch
construct. As a result the code is more difficult to understand and to maintain.
The second solution embeds each behaviour in a different class. The main class
must have an attribute that refers to the object implementing the currently
selected behaviour. All the different behaviour classes implement the common
interface
Behavior
. In other words, the main class can be linked to any object that
conforms to the contract in the
Behavior
interface.
The binding of the interface to a specific behaviour is carried out at run time.
This is in the nature of polymorphism.
Changing
```
Interface
ppp
Behavior
!
perform()
!
setBehavior()
+doPerform()
FirstBehavior
SecondBehavior
!
doPerform()
!
doPerform()
The above classes can be implemented as follows:
public class
Changing {
Behavior behavior
#
null
;
public void
setBehavior(Behavior newBehavior)
{ behavior
#
newBehavior; }
public void
perform(){
if
(behavior !
#
null
)
behavior.doPerform();
}
}
public interface
Behavior{
void
doPerform();
}
public class
FirstBehavior
implements
Behavior {
public
doPerform(){/* B1 */ }
}
public class
SecondBehavior
implements
Behavior {
public
doPerform(){/* B2 */ }
}
The following code fragment shows the use of this solution:
Changing chObject
#
new
Changing(;
chObject.setBehavior(
new
FirstBehavior());
chObject.perform();
The main advantage of this approach is that adding a new behaviour is just a
matter of defining a new class; this means that the main class is independent of
the different behaviours. On the other hand, this approach uses many more
classes making it more complex.