Author: techfox9

Design Patterns – Strategy pattern (Behavioral) basic example..

Tuesday, May 8th, 2007 @ 9:20 am

A possible usage scenario without thinking ‘Strategy’ ..


// Example without using the Strategy pattern

public class WithOutStrategy { 

    public void doSomething(int theSwitch) { 

        if ( theSwitch == 0 ) { 
            AClass ac = new AClass(); 
            ac.doit(); 
        } 

        if ( theSwitch == 1 ) { 
            BClass bc = new BClass(); 
            bc.doit(); 
        } 

    } 

    public static void main(String[] args) { 

        WithOutStrategy sb = new WithOutStrategy(); 
        sb.doSomething(0); 
        sb.doSomething(1); 
    } 

} 

class AClass { 

    public void doit() { 
        System.out.println(">> doit A"); 
    } 

} 

class BClass { 

    public void doit() { 
        System.out.println(">> doit B"); 
    } 

}

And a better way of doing it with ‘Strategy’..


// Example using Strategy

public class WithStrategy { 

    public void doSomething(OClass oc) { 
        oc.doit(); 
    } 

    public static void main(String[] args) { 

        WithStrategy ows = new WithStrategy(); 
        OClass oc = null; 

        oc = new AClass(); 
        ows.doSomething(oc); 

        oc = new BClass(); 
        ows.doSomething(oc); 
    } 

} 

// Options class 

abstract class OClass { 
    public abstract void doit(); 
} 

class AClass extends OClass { 

    public void doit() { 
        System.out.println(">> doit A"); 
    } 

} 

class BClass extends OClass { 

    public void doit() { 
        System.out.println(">> doit B"); 
    } 

}

Engineering, Software


 


Comments are closed.