How to use anonymous internal classes to transform factory methods in section 8.8 from the ground up in java-7.8
In this section, we will revisit the factory method and use the anonymous internal class to transform the factory method.
Previous Article: 7.8 interface and factory Model
Example of the last factory method:
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() {return new ServiceImpl();}}public class Test {public static void test(ServiceFactory factory) {Service service = factory.getService();service.doSomeThing();}public static void main(String[] args) {test(new ServiceFactoryImpl());}}
We will transform the above factory method through the anonymous internal class to hide the implementation code of the factory implementation code.
package com.ray.ch07;interface Service {void doSomeThing();}interface ServiceFactory {Service getService();}class ServiceImpl implements Service {private ServiceImpl() {}@Overridepublic void doSomeThing() {}public static ServiceFactory getFactory() {return new ServiceFactory() {@Overridepublic Service getService() {return new ServiceImpl();}};}}public class Test {public static void test(ServiceFactory factory) {Service service = factory.getService();service.doSomeThing();}public static void main(String[] args) {test(ServiceImpl.getFactory().getService());}}
The above Code uses an anonymous internal class to hide the factory implementation and replace some of the Code, because an implementation corresponds to a factory.
Summary: This section describes how to use an anonymous internal class to transform a factory.