Design Patterns: Strategy Pattern

   Before all, we have to understand first what a Design Pattern is. A Design pattern is a form to deal with object in the OOP so that it will be easy to change or to upgrade our information system and provide a way to let some part of system vary independently of all another part.

    In the design pattern study we have to know some vocabulary as:
    -Abstraction: a concept or idea not associates with any instance.
    -Encapsulation:  which is the restriction to access some of the object’s components or bundling of data with the method operating in data
    -Polymorphism: Is the ability to create a variable, a function or an object that has more than one form.
    -Inheritence: which is an “IS A” relationship generally used as “extends” in OOP.

Design Patterns principles like:
    -Identify the aspects of your application that vary and separate them from those what stays the same;
    -Program to an interface not to an implementation
    -Favor composition over inheritence

The Strategy Pattern defines a family of algorithm, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from client that uses it.

Here is a small application of this Pattern, The Duck program.

public class FlyingWithWings implements FlyBehavior {
	public void fly(){
		System.out.println("I am flying with wings");
	}	
}

public class FlyNoWay implements FlyBehavior {
	public void fly(){
		System.out.println("I can't fly");
	}
}


public interface FlyBehavior {

	public void fly();
}


public class Quack implements QuackBehavior {
	public void quack(){
		System.out.println("I am quacking");
	}
}


public class MuteQuack {
	public void quack(){
		System.out.println("Mute quack");
	}
}


public class Squeak {
	public void quack(){
		System.out.println("I am squeaking");
	}
}


public interface QuackBehavior {
	public void quack();
}


public abstract class Duck {
	
	FlyBehavior flybehavior;
	QuackBehavior quackbehavior;
	
	public void performFly(){
		flybehavior.fly();
	}
	
	public void performQuack(){
		quackbehavior.quack();
	}
}



public class MallardDuck extends Duck {
	public MallardDuck(){
		quackbehavior =  new Quack();
		flybehavior = new FlyNoWay();
	}
	
	public void display(){
		System.out.println("I am a real mallardDuck");
	}
}


public class MiniDuckSimulator {
	public static void main(String[] args) {
		Duck mallard = new MallardDuck();
		mallard.performFly();
		mallard.performQuack();
	}
}

猜你喜欢

转载自sasipa90.iteye.com/blog/1150701