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!");}}}
阅读全文
0 0
- Java interface 接口的使用理解
- java 接口interface的使用
- java接口interface理解,接口作用
- 接口 Interface的使用
- Java Interface 的理解
- java入门教程-5.4Java接口(interface)的概念及使用
- 接口interface的使用(一)
- Java 接口interface的详解
- Java Interface接口的应用
- 混乱的关于接口(Interface)的理解!
- Java中接口(Interface)的定义和使用
- C#中接口(interface)的理解
- C#中接口(interface)的理解
- C#接口(interface)的理解
- 个人对interface接口的理解
- JAVA中interface的理解
- C# interface 接口理解
- C# interface 接口理解
- Java基础——Java内存模型和垃圾回收机制
- 密码编码学初探——传统加密技术
- MYSQL(主主)双机热备+Keepalived实现故障切换
- CSS hover 同级元素
- rdo默认安装的用户,使用su
- Java interface 接口的使用理解
- Bootstrap实现网站首页(Bootstrap概述)
- 从输入url到呈现页面
- 【传智播客郑州校区分享】斐波那契函数的优化
- MongoDB常用脚本
- InputStreamWrite:字符流
- 海量数据处理
- spring事务传播属性,隔离级别
- 用.lng文件翻译成中文