1:举例
public static class HttpCommunication{ public void communicate(){ Log.d("test", "HttpCommunication"); } } public static class Test{ public void test(HttpCommunication httpCommunication){ httpCommunication.communicate(); } } public static void main(String[] args) { Test test = new Test(); HttpCommunication httpCommunication = new HttpCommunication(); test.test(httpCommunication); }
类HttpCommunication作为被调用者,Test作为调用者,理解为用户,这时候的参数是HttpCommunication ,通讯为http方式。
如果有一天,我不想要Http为通讯方式,想换一个socket:
public class SocketCommunication{ public void communicate(){ Log.d("test", "SocketCommunication"); } }
对于Test类来说,即对于用户类来说,其实是不想有变化的,但是因为test方法的参数是固定的HttpCommunication,导致想要增加一种通信方式的时候
,必须修改Test类,这就违背了低耦合高内聚的原理。
以下是不使用接口的情况:
public static class HttpCommunication{ public void communicate(){ Log.d("test", "HttpCommunication"); } } public static class SocketCommunication{ public void communicate(){ Log.d("test", "SocketCommunication"); } } public static class Test{ public void test(HttpCommunication httpCommunication){ httpCommunication.communicate(); } public void test2(SocketCommunication socketCommunication){ socketCommunication.communicate(); } } public static void main(String[] args) { Test test = new Test(); /* HttpCommunication httpCommunication = new HttpCommunication(); test.test(httpCommunication);*/ SocketCommunication socketCommunication = new SocketCommunication(); test.test2(socketCommunication); }
修改为使用接口如下:最重要的就是对于Test类,即使用者来说,不关心你添加了几种使用方式,
不需要去修改Test类里面的test()方法。
test持有的是接口communication,test只关心communcation调用的结果。任何所有实现了Communication的类都可以传进来,并且
可以给我返回结果,至于过程是怎么实现的,test不关心。
可以想象成Communication相关的是一个模块,Test是一个模块,Communication里面的改变,不应该是Test有改变,才是低耦合。
public interface Communication{ public void communicate(); } public static class HttpCommunication implements Communication{ @Override public void communicate() { Log.d("test", "HttpCommunication"); } } public static class SocketCommunication implements Communication{ @Override public void communicate() { Log.d("test", "SocketCommunication"); } } public static class Test{ public void test(Communication communication){ communication.communicate(); } } public static void main(String[] args) { Test test = new Test(); Communication httpCommunication = new HttpCommunication(); test.test(httpCommunication); Communication socketCommunication = new SocketCommunication(); test.test(socketCommunication); }
标签:void,编程,接口,Test,static,面向,test,public,HttpCommunication From: https://www.cnblogs.com/wnpp/p/17143117.html