标签:
定义:定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。
UML图示:
?
代码示例:
/**封装飞的行为*/
public interface FlyBehavior {
????public void fly();
}
public class FlyNoWings implements FlyBehavior{
????@Override
????public void fly() {
????????// TODO Auto-generated method stub
????????System.out.println("fly not wings!");
????}
}
public class FlyNoWings implements FlyBehavior{
????@Override
????public void fly() {
????????// TODO Auto-generated method stub
????????System.out.println("fly not wings!");
????}
}
?
/**封装叫的行为*/
public interface QuackBehavior {
????public void quack();
}
public class Quack implements QuackBehavior{
????@Override
????public void quack() {
????????// TODO Auto-generated method stub
????????System.out.println("quack...");
????}
}
public class Squeak implements QuackBehavior{
????@Override
????public void quack() {
????????// TODO Auto-generated method stub
????????System.out.println("squeak...");
????}
}
?
/**使用封装好的算法族*/
public abstract class Duck {
????private FlyBehavior mFlyBehavior = null;
????private QuackBehavior mQuackBehavior = null;
????public void fly(){
????????if(mFlyBehavior != null)
????????????mFlyBehavior.fly();
????}
????public void quack(){
????????if(mQuackBehavior != null){
????????????mQuackBehavior.quack();
????????}
????}
????public abstract void display();
????public void setQuackBehavior(QuackBehavior quack){
????????mQuackBehavior = quack;
????}
????public void setFlyBehavior(FlyBehavior fly){
????????mFlyBehavior = fly;
????}
}
?
public class RubberDuck extends Duck{
????public RubberDuck() {
????????// TODO Auto-generated constructor stub
????????setFlyBehavior(new FlyNoWings());
????????setQuackBehavior(new Squeak());
????}
????@Override
????public void display() {
????????// TODO Auto-generated method stub
????????System.out.println("display rubber duck");
????}
}
public class RedHeadDuck extends Duck{
????public RedHeadDuck() {
????????// TODO Auto-generated constructor stub
????????setFlyBehavior(new FlyWithWings());
????????setQuackBehavior(new Quack());
????}
????@Override
????public void display() {
????????// TODO Auto-generated method stub
????????System.out.println("display red head duck");
????}
}
?
public class Main {
????public static void main(String[] args) {
????????Duck redHeadDuck = new RedHeadDuck();
????????Duck rubberDuck = new RubberDuck();
????????redHeadDuck.fly();
????????redHeadDuck.quack();
????????redHeadDuck.display();
????????rubberDuck.fly();
????????rubberDuck.quack();
????????rubberDuck.display();
????}
}
?
测试结果:
fly with wring!
quack...
display red head duck
fly not wings!
squeak...
display rubber duck
?
????
标签:
原文地址:http://www.cnblogs.com/jaden/p/4391152.html