Java interface 接口的使用理解

来源:互联网 发布:php beast 怎么用 编辑:程序博客网 时间:2024/05/16 12:55

很多人都比较疑惑,为什么要使用接口。 在我个人理解来说,接口其实是一套协议,一套契约,是框架开发者与使用者之间的一种契约,框架开发者/架构师承诺,只要你符合我的契约,也就是实现接口那么我必然可以支持你的拓展类。当框架设计者认为这一个类需要被灵活的拓展用于适应需求,在提供一个默认的解决方案的同时,提出了这种契约,以便使用者拓展。可以看看下面的例子,就比较容易理解,接口定义的意义。框架设计者允许使用者对框架进行拓展,但是用户不能自行修改,必须遵守一套准则,一个契约,框架才能正常运转。


/** * @author zsf */public class Framework {/** * 框架初始化,框架初始化策略支持框架使用者自行拓展 * 默认使用DefaultStrategy * @param initStrategy 接口类 */public void init(InitStrategy initStrategy)throws Exception{if(initStrategy == null){//如果初始化策略为空,使用默认初始化策略initStrategy = new DefaultStrategy();try {initStrategy.init();}catch (Exception e) {throw new Exception("框架初始化异常");}}}public interface InitStrategy{public void init();}/** * 默认初始化策略 */class DefaultStrategy implements InitStrategy{@Overridepublic void init() {System.out.println("Default init strategy!");}}public static void main(String[] args) {initByDefaultInitStrategy();initByUserInitStrategy();}/** * 初始化默认策略 */public static void initByDefaultInitStrategy(){Framework framework = new Framework();try {framework.init(null);} catch (Exception e) {e.printStackTrace();}}/** * 初始化用户拓展策略 */public static void initByUserInitStrategy(){Framework framework = new Framework();InitStrategy userStrategy = new UserInitStrategy();try {framework.init(userStrategy);} catch (Exception e) {e.printStackTrace();}}/** * 用户自定义策略 */static class UserInitStrategy implements InitStrategy{@Overridepublic void init() {System.out.println("User's InitStrategy!");}}}