Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the similarities between the Template Method and Strategy design patterns

is this an example of TemplateMethod Pattern??

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 then what is the advantage of using this pattern than strategy pattern??

Strategy 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();
    }
}

What I noticed is Strategy pattern encapsulate what varies unlike TemplateMethod Pattern lets the subclassed handles what varies.

like image 319
user1364686 Avatar asked Apr 29 '12 21:04

user1364686


1 Answers

Strategy pattern defines a family of algorithms and makes them interchangeable. Client code can use different algorithms since the algorithms are encapsulated.

Template method defines the outline of an algorithm and lets subclasses part of the algorithm's implementation. So you can have different implementations of an algorithms steps but retain the algorithm's structure

So as you can see the intent is different in each pattern. So it is not a matter of advantage of one over the other.

like image 53
Cratylus Avatar answered Sep 23 '22 20:09

Cratylus