设计模式--缺省适配器模式

来源:互联网 发布:淘宝关闭无法激活 编辑:程序博客网 时间:2024/06/05 09:18

Structural 模式 如何设计物件之间的静态结构,如何完成物件之间的继承、实 现与依赖关系,这关乎着系统设计出来是否健壮(robust):像是易懂、易维护、易修改、耦合度低等等议题。Structural 模式正如其名,其分类下的模式给出了在不同场合下所适用的各种物件关系结构。

  • Default Adapter 模式
  • Adapter 模式
  • Bridge 模式
  • Composite 模式
  • Decorator 模式
  • Facade 模式
  • Flyweight 模式
  • Proxy 模式

很多情况下,一个具体类去实现一个接口,但是又不是需要实现接口中所有的方法,只需要部分方法,但是实现接口的时候,强制实现了所有的方法,这样就导致了这个具体类含有许多空方法.这是一种浪费,也会导致混乱,所以就产生了缺省适配器模式.

下面我们定义一个人接口(IPerson)

[java] view plain copy
 print?
  1. public interface IPerson{  
  2.     String getName() ;  
  3.     void goToSchool() ;  
  4.     void work() ;  
  5.     void eat() ;  
  6. }  

当需要一个学生的具体类时,我们会发现,如果继承IPerson接口的话,那么work()这个方法就必须空着,所以这里我们先定义一个抽象的缺省适配器类实现IPerson接口.

[java] view plain copy
 print?
  1. public abstract class PersonAdapter{  
  2.     public String getName(){} ;  
  3.     public void goToSchool(){} ;  
  4.     public void work(){} ;  
  5.     public void eat() ;  
  6. }  

接下来我们再实现我们具体的学生类(Student)

[java] view plain copy
 print?
  1. public class Student extends PersonAdapter{  
  2.     private String name = null ;  
  3.     public Student(String name){  
  4.         this.name = name ;  
  5.     }  
  6.     public String getName(){  
  7.         return name ;  
  8.     }  
  9.     public void goToSchool(){  
  10.         System.out.println("go to school !") ;  
  11.     }  
  12.     public void eat(){  
  13.         System.out.println("eating") ;  
  14.     }  
  15. }  

下面是类结构图

img



原创粉丝点击