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 }

 

 

  

 

posted @ 2015-07-28 15:21  cstar0818  阅读(369)  评论(0编辑  收藏  举报