【设计模式】策略模式

策略模式
具体代码
public interface ActionInterface {
/**
* 吃喝拉撒 接口
*/
void eat();

void drink();

void put();

void sleep();

}

public class Dog implements ActionInterface {
@Override public void eat() {
System.out.println(“狗吃”);
}

@Override public void drink() {
    System.out.println("狗喝");
}

@Override public void put() {
    System.out.println("狗放");
}

@Override public void sleep() {
    System.out.println("狗睡");
}

}

public class Person implements ActionInterface {
@Override public void eat() {
System.out.println(“人吃”);
}

@Override public void drink() {
    System.out.println("人喝");
}

@Override public void put() {
    System.out.println("人放");
}

@Override public void sleep() {
    System.out.println("人睡");
}

}

public class Context {
ActionInterface actionInterface;

public Context(ActionInterface actionInterface) {
    this.actionInterface = actionInterface;
}

public void action(){
    actionInterface.eat();
}

public void drink(){
    actionInterface.drink();
}
public void put(){
    actionInterface.put();
}
public void sleep(){
    actionInterface.sleep();
}

}

主方法
public class MainMethod {
public static void main(String[] args) {
Context context = new Context(new Dog());
context.drink();

    context=new Context(new Person());
    context.drink();
}

}

运行效果

狗喝
人喝

接口实现一定都会实现或者留空

策略模式优点:

扩展性好,可以在不修改对象结构的情况下,为新的算法进行添加新的类进行实现;
灵活性好,可以对算法进行自由切换;

策略模式缺点:

使用策略类变多,会增加系统的复杂度。;
客户端必须知道所有的策略类才能进行调用;

使用场景:

如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为;
一个系统需要动态地在几种算法中选择一种;
如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值