从头认识java-7.8 接口与工厂模式

来源:互联网 发布:蒙泰初始化端口 编辑:程序博客网 时间:2024/06/05 03:23

这一章节我们来聊聊接口与工厂模式之间的关系。

接口是实现多重继承的途径,生成遵循某个接口协议的对象的典型方式是工厂设计模式。

这种设计模式使得接口与实现完全分开。

package com.ray.ch07;interface Service {void doSomeThing();}interface ServiceFactory {Service getService();}class ServiceImpl implements Service {@Overridepublic void doSomeThing() {}}class ServiceFactoryImpl implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn null;}}public class Test {public static void test(ServiceFactory factory) {Service service = factory.getService();service.doSomeThing();}public static void main(String[] args) {test(new ServiceFactoryImpl());}}


从上面的代码看出,我们只是在最后一步new的时候,才把实现类放进去,其他的代码基本以接口来实现,从而把接口与实现完全分离,这样有利于Test这个代码的重复使用。

那么,怎么使用呢?

我们下面给出例子:(就是有多个Service的时候,Test就可以重复使用了)

package com.ray.ch07;interface Service {void doSomeThing();}interface ServiceFactory {Service getService();}class ServiceImpl implements Service {@Overridepublic void doSomeThing() {}}class ServiceFactoryImpl implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn null;}}class ServiceImpl2 implements Service {@Overridepublic void doSomeThing() {}}class ServiceFactoryImpl2 implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn null;}}public class Test {public static void test(ServiceFactory factory) {Service service = factory.getService();service.doSomeThing();}public static void main(String[] args) {test(new ServiceFactoryImpl());test(new ServiceFactoryImpl2());}}


当我们有n个Service的实现类时,我们只需要写一份Test代码,然后根据实际情况new不同的实现类,这样就可以重复使用Test的代码来测试。

 

最后,工厂模式这些设计模式还有其他很多的应用,我们将在另外的一个课程里面讨论,这里不再做详细展开。

 

总结:这一章节主要讨论了接口与设计模式之间的关系。

 

这一章节就到这里,谢谢。

-----------------------------------

目录

 

 

4 0