天天看點

政策模式和狀态模式的差別

政策模式和狀态模式的類圖相同,目的都是為了解耦,但是還有很多的差別

政策模式

1. public classs 我{
2. 
3. //打扮
4. void dressUp();
5. 
6. //娛樂
7. void entertainment(Grade grade){
8.       grade.entertainment();
9.    }
10. 
11. //買車
12. void buyCar();
13. 
14. 
15. }      

政策接口

1. public interface Grade(
2. 
3. public void hasMoney();
4. 
5. )      

政策實作

1. public class has10 implements Grade{
2. public void entertainment(){
3.           system.out.print("10塊錢保健啥,洗個澡吧")
4.        }
5. }      
1. public class has100 implements Grade{
2. public void entertainment(){
3.           system.out.print("100塊,按個腳吧")
4.        }
5. }      
1. public class has1000 implements Grade{
2. public void entertainment(){
3.           system.out.print("1000塊,那就來個大保健吧")
4.        }
5. }      

調用

1. public class Client {
2. 
3. public static void main(String[] args) {
4.           我 me = new 我();
5.           me.entertainment(new has10());
6.           me.entertainment(new has100());
7.        }      

可以看到隻有針對娛樂有不同方法,而其他的項目沒有影響,此為政策模式

狀态模式

我類的修改

1. public classs 我{
2. 
3. private Grade grade;
4. 
5. public void setGrade(Grade grade) {
6. this.grade= grade;
7.     }
8. //打扮
9. void dressUp(
10.       grade.dressUp();
11.    );
12. 
13. //娛樂
14. void entertainment(Healthcare healthcare){
15.       grade.dressUp();
16.    }
17. 
18. //買車
19. void buyCar(
20.      grade.buyCar();
21.    );
22. 
23. 
24. }      
1. public static void main(String[] args) {
2.           我 me = new 我();
3. me.setGrade(new has10());
4. me.entertainment();
5. me.dressUp();
6. me.setGrade(new has100());
7. me.entertainment();
8.        }      

可以看到每一次的變化,我的整個檔次都變了,無論是娛樂還是穿衣服,是以此為狀态模式

繼續閱讀