java接口应用—策略设计模式

     策略模式:定义了一系列算法,将每一种算法封装起来并可以相互替换使用,策略模式让算法独立于使用它的客户应用而独立变化

       strategy pattern:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

 

oo设计原则:

1、面向接口编程(面向抽象编程)

2、封装变化

3、多用组合,少用继承

 

例子:

 1 package practice1;
 2 
 3 public class Test9 {
 4 
 5     public static void main(String[] args) {
 6           Duck duck=new BlackDuck("黑鸭子", new FlyImpl());
 7           duck.fly();
 8           
 9           Duck duck2=new ModeDuck("白鸭子", new NotFlyImpl());
10           duck2.fly();
11     }
12 }
13 class Duck{
14     private String name;
15     private Flyable flyable;//把接口作为属性
16         
17     public Duck(String name,Flyable flyable){
18         this.name=name;
19         this.flyable=flyable;
20     }
21     public void fly(){
22         flyable.fly();
23     }
24 }
25 
26 class BlackDuck extends Duck{
27 
28     public BlackDuck(String name, Flyable flyable) {
29         super(name, flyable);
30     }
31     
32 }
33 class ModeDuck extends Duck{
34 
35     public ModeDuck(String name, Flyable flyable) {
36         super(name, flyable);
37     }
38 
39 }
40 //接口
41 interface Flyable{
42     public void fly();
43 }
44 
45 class FlyImpl implements Flyable{
46 
47     @Override
48     public void fly() {
49        System.out.println("会飞");    
50     }
51     
52 }
53 
54 class NotFlyImpl implements Flyable{
55 
56     @Override
57     public void fly() {
58         System.out.println("不会飞");
59     }
60     
61 }

 

 

  

 

转载于:https://www.cnblogs.com/chenxing818/p/4682903.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值