Make sure method A is called after every call to B (abstract implemented method)?

Having this tasteful class

public abstract class CakeSkill { //.. boolean cherry=false; private void finalMandatoryTouch() { cherry=true; } abstract public void cook(); } 

The class that extends it will be something like

  class Cheff extends CakeSkill { //.. void cook() { //..Secret recipe } } 

But of course it won’t work,

finalMandaroryTouch () was not called, then no cake will end in cherry.

[EDIT]

It may be a solution.

  class MemoriousCheff extends CakeSkill { //.. void cook() { //..Secret recipe finalMandatoryTouch(); } } 

but requires:

  • Cheff has an excellent memory that don't forget to call finalMandatoryTouch ()
  • Creating finalMandatoryTouch () for protection (at least)

[/ EDIT]

It would be great! (but not Java) if something like this can be done

  abstract public void cook() { @implementedMethod finalMandatoryTouch(); } 

How can this useful functionality be implemented?

Thank you very much

+4
source share
5 answers

Change cook to the protected cookImpl method, then enter the public final method called cook:

 public final void cook() { cookImpl(); finalMandatoryTouch(); } protected abstract void cookImpl(); 

This way, the subclass only needs to worry about cookImpl , but the calling callers get the cherry on top. Callers in more than one package or class hierarchy do not even see cookImpl , so they cannot call it directly.

This is a template template template , basically.

+10
source

He called the template Method template .

 final public void cook() { mainCookRecipe(); finalMandatoryTouch(); } abstract public void mainCookRecipe(); 
+3
source
 public abstract class CakeSkill { public void cook() { doCook(); finalMandatoryTouch(); } protected abstract doCook(); private finalMandatoryTouch() { ... } } 

Etc.

+1
source

You can change your cook() method to the actual method, and then call the separate abstract method, as well as your finalMandatoryTouch() method.

In your abstract class:

  public void cook() { specificCook(); finalMandatoryTouch(); } abstract void specificCook(); 
+1
source

Inheritance seems to be the wrong way to model your problem. In Java, you can only inherit one class, and since it is also a very static relationship, it limits your chef with the skills that he can perform.

It’s best to use a composition. Culinary skills can be strategies that a chef performs:

 interface CookingSkill { void cook(); } class CakeSkill implements CookingSkill { private boolean cherry = false; private void finalMandatoryTouch() { cherry = true; } public void cook() { //... finalMandatoryTouch(); } } class Chef { private CookingSkill cookingSkill; // getters and setters ... public void cook() { // ... cookingSkill.cook(); // ... } } 

Now you can assign different culinary skills to your chef.

+1
source

All Articles