How to use anonymous internal classes to transform factory methods in section 8.8 from the ground up in java-7.8

Source: Internet
Author: User

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.

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.