定义:定义了算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
1、找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。(把会变化的部分取出并“封装”起来,好让其他部分不会受到影响)
2、针对接口编程,而不是针对实现编程。(行为将被放在分开的类中,此类专门提供某行为接口实现,这样超类就不在需要知道行为的实现细节)在不涉及java interface的情况下,“针对接口编程”,关键就在多态。
3、多用组合,少用继承。(“有一个”可能比“是一个”更好)
1 package com.duck; 2 3 public abstract class flybehavior { 4 public abstract void fly(); 5 } 6 7 package com.duck; 8 9 public class flynoway extends flybehavior { 10 11 @Override 12 public void fly() { 13 // TODO Auto-generated method stub 14 System.out.println("can not fly"); 15 } 16 17 } 18 19 package com.duck; 20 21 public class flywithwings extends flybehavior { 22 23 @Override 24 public void fly() { 25 // TODO Auto-generated method stub 26 System.out.println("fly with wings"); 27 } 28 29 } 30 31 package com.duck; 32 33 public abstract class quackbeh { 34 public abstract void quack(); 35 } 36 37 package com.duck; 38 39 public class guguquack extends quackbeh { 40 41 @Override 42 public void quack() { 43 // TODO Auto-generated method stub 44 System.out.println("gugu~~"); 45 } 46 47 } 48 49 package com.duck; 50 51 public class mutequack extends quackbeh { 52 53 @Override 54 public void quack() { 55 // TODO Auto-generated method stub 56 System.out.println("~~"); 57 } 58 59 } 60 61 package com.duck; 62 63 public class squack extends quackbeh { 64 65 @Override 66 public void quack() { 67 // TODO Auto-generated method stub 68 System.out.println("zhizhi~~"); 69 } 70 71 } 72 73 package com.duck; 74 75 public abstract class duck { 76 private flybehavior fb; 77 private quackbeh qb; 78 79 80 public flybehavior getFb() { 81 return fb; 82 } 83 84 public void setFb(flybehavior fb) { 85 this.fb = fb; 86 } 87 88 public quackbeh getQb() { 89 return qb; 90 } 91 92 public void setQb(quackbeh qb) { 93 this.qb = qb; 94 } 95 96 public abstract void display(); 97 98 public void performFly(){ 99 fb.fly(); 100 } 101 102 public void performQuack(){ 103 qb.quack(); 104 } 105 } 106 107 package com.duck; 108 109 public class muteduck extends duck { 110 111 public muteduck(){ 112 this.setFb(new flywithwings()); 113 this.setQb(new mutequack()); 114 } 115 116 @Override 117 public void display() { 118 // TODO Auto-generated method stub 119 System.out.println("no quack~~"); 120 } 121 122 } 123 124 package com.duck; 125 126 public class initial { 127 128 public static void main(String[] args) { 129 // TODO Auto-generated method stub 130 duck dk = new muteduck(); 131 dk.performFly(); 132 dk.performQuack(); 133 dk.display(); 134 135 dk.setFb(new flynoway()); 136 dk.performFly(); 137 dk.performQuack(); 138 dk.display(); 139 } 140 141 }