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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值