Definition-defines a family of algorithms, encapsulate each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Key points: separate different parts/behaviors and encapsulate each part/behavior
Advantage: not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime .
Example1 (quote from First Head In Design Pattern) :

//inteface code
//FlyBehavior.java
public interface FlyBehavior ...{
public void Fly();
}
//QuakeBehavior.java
public interface QuakeBehavior ...{
public void Quake();
}
//Duck.java
public abstract class Duck ...{
FlyBehavior flyBehavior;
QuakeBehavior quakeBehavior;
public void performFly()
...{
flyBehavior.Fly();
}
public void performQuake()
...{
quakeBehavior.Quake();
}
public abstract void Display();
public void SetFlyBehavior(FlyBehavior flyb)
...{
this.flyBehavior = flyb;
}
public void SetQuakeBehavior(QuakeBehavior quakeb)
...{
this.quakeBehavior = quakeb;
}
}

public class FlyWithWings implements FlyBehavior ...{

public void Fly() ...{
System.out.println("Fly with wings");
}
}
public class FlyWithNoWings implements FlyBehavior ...{
public void Fly() ...{
System.out.println("Fly without wings");
}
}
public class NormalQuake implements QuakeBehavior ...{
@Override
public void Quake() ...{
System.out.println("Normal Quake");
}
}
public class MuteQuake implements QuakeBehavior ...{
@Override
public void Quake() ...{
// TODO Auto-generated method stub
System.out.println("Mute Quake");
}
}
public class MallardDuck extends Duck ...{
@Override
public void Display() ...{
// TODO Auto-generated method stub
System.out.println("I'm Mallard Duck");
}
}
public class MiniDuckSimulator extends Duck ...{
@Override
public void Display() ...{
// TODO Auto-generated method stub
System.out.println("I'm mini-duck");
}
}//display result

public class Main ...{

public static void main(String[] args) ...{
// TODO Auto-generated method stub
Duck mallardDuck=new MallardDuck();
Duck miniDuck=new MiniDuckSimulator();
FlyBehavior flyWithWings=new FlyWithWings();
FlyBehavior flyWithNoWings=new FlyWithNoWings();
QuakeBehavior normalQuake=new NormalQuake();
QuakeBehavior muteQuake=new MuteQuake();
//Customize
mallardDuck.SetFlyBehavior(flyWithWings);
mallardDuck.SetQuakeBehavior(normalQuake);
miniDuck.SetFlyBehavior(flyWithNoWings);
miniDuck.SetQuakeBehavior(muteQuake);
//perfomance and display
mallardDuck.Display();
mallardDuck.performFly();
mallardDuck.performQuake();
miniDuck.Display();
miniDuck.performFly();
miniDuck.performQuake();
}
}Example2 (talk about PetShop4.0 developed by MS):
When inserting Order, PetShop System enable user customize which strategy he want to use, synchronization or asynchronization. i.e. the insert-order strategy is changeable at runtime, determined by user himself.
本文通过定义一组算法并将其封装成独立的类,使它们可以互相替换,介绍了策略模式的概念。通过两个例子展示了如何实现策略模式:一是模拟鸭子的行为,二是电子商务系统中订单插入策略的选择。
954

被折叠的 条评论
为什么被折叠?



