博客现已迁移到:http://henderyblog.sinaapp.com 欢迎访问
接口是实现多重继承的途径,而生成遵循某个接口的对象的典型方式就是工厂模式。工厂模式的典型应用就是创建框架。下面是通用的工厂模式实现代码:
interface Service { void method1(); void method2(); } interface ServiceFactory { Service getService(); } class Implemtation1 implements Service { public void method1() { System.out.println("implemtation1 method1"); } public void method2() { System.out.println("implemtation method2"); } } class ImplementFactory1 implements ServiceFactory { public Service getService()//工厂对象上调用创建方法 { return new Implemtation1();//返回接口的一个实现对象 } } class Implemtation2 implements Service { public void method1() { System.out.println("implemtation2 method1"); } public void method2() { System.out.println("implemtation2 method2"); } } class ImplementFactory2 implements ServiceFactory { public Service getService() { return new Implemtation2();//返回接口的一个实现对象 } } public class Factories { public static void serviceConsumer(ServiceFactory factory) { Service service = factory.getService();//得到实现接口的实例对象 service.method1(); service.method2(); } public static void main(String[] args) { serviceConsumer(new ImplementFactory1()); serviceConsumer(new ImplementFactory2()); } }
上面的工厂模式是使用类实现的,过程比较复杂,实际上我们可以使用匿名内部类去实现,可以简化代码,同时又可以隐藏细节,具体代码如下:interface Service { void method1(); void method2(); } interface ServiceFactory { Service getService(); } class Implementation1 implements Service { //public不能省略,因为接口中的所有元素默认是public的 public void method1() { System.out.println("Implementation1 method1"); } public void method2() { System.out.println("Implementation1 method2"); } /*直接使用了new ServiceFactory() 似乎不对,实际上是使用匿名内部类生成了一个ServiceFactory类型的对象
*在接口的后面紧跟着接口的实现,也就是生成了一个匿名内部类,得到的接口的实现类。
*/同时实例化了接口的方法,可谓一招三用 public static ServiceFactory factory = new ServiceFactory(){ public Service getService() { return new Implementation1(); } }; } class Implementation2 implements Service { public void method1() { System.out.println("Implementation2 mtethod1"); } public void method2() { System.out.println("Implemention2 method2"); } /*2中的factory不设置为static类型的,在main方法中需使用对象调用
*/同时不再用public修饰,使用了默认访问权限,也就是包访问权限 ServiceFactory factory = new ServiceFactory(){ public Service getService() { return new Implementation2(); } }; } public class Factory { public static void serviceConsumer(ServiceFactory factory) { Service s = factory.getService(); s.method1(); s.method2(); } public static void main(String[] args) { serviceConsumer(Implementation1.factory);//通过类名直接调用factory域 serviceConsumer(new Implementation2().factory);//使用对象的方式调用factory域 } }