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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With