What are the similarities between templates and strategy templates

is an example of TemplateMethod ??

public abstract class Character{

    public final void useWeapon(){
        useBusterSword();
        useMateriaBlade();
        useUltimateWeapon();
    }

    public abstract void useBusterSword();
    public abstract void useMateriaBlade();
    public abstract void useUltimateWeapon();
}

public class Cloud extends Character{

    public void useUltimateWeapon() {
        System.out.println("Change Weapon to Ultima Weapon");
    }


    public void useBusterSword() {

    }


    public void useMateriaBlade() {

    }
}


public class TestGame {
    public static void main(String[] args){
        Character cloud = new Cloud();
        cloud.useWeapon();
    }
}

If so, what is the advantage of using this template than the strategy template?

Strategic pattern

public class Character {
    WeaponBehavior w;
    public void setWeaponBehavior(WeaponBehavior wb){
        w = wb;
    }

    public void useWeapon(){
        w.useWeapon();
    }
}

public class Cloud extends Character{

    public Cloud(){
        w = new UltimaWeapon();
    }

}


public interface WeaponBehavior {
    public void useWeapon();
}

public class UltimaWeapon implements WeaponBehavior {
    public void useWeapon() {
        System.out.println("Change Weapon to UltimaWeapon");
    }

}

public class BusterSword implements WeaponBehavior {
    public void useWeapon() {
        System.out.println("Change Weapon to MateriaBlade");
    }

}

public class MateriaBlade implements WeaponBehavior {
    public void useWeapon() {
        System.out.println("Change Weapon to MateriaBlade");
    }

}

public class TestGame {
    public static void main(String[] args){
        Character c = new Cloud();
        c.useWeapon();
    }
}

I noticed that the strategy template encapsulates what changes, unlike the TemplateMethod Pattern, allows subclasses to handle what changes.

+5
source share
4 answers

Strategypattern defines a family of algorithms and makes them interchangeable. Client code can use different algorithms because the algorithms are encapsulated.

Template . , ,

, . , .

+3

, , .

.

. -., :

  • coocked smbd

java Recipe

void cook(){
  takeIngridients();
  putIt();  // abstract
  heat();  //abstract
  giveFood();
}

PanRecipe extends Recipe . GrillRecipe . grillRecipe.cook(), takeIngridients giveFood.

+2

, , , "", .

, , , , .

, , , , , , setter , .

, , .

+1

:

  • .
  • , -

.

:

  • Inheritance Strategy
  • Template, , . , ,
  • ,

:

JDK , ,

Strategy .

+1

All Articles