[JavaSE] Use anonymous inner classes

Anonymous inner classes are also often used in java. It not only simplifies the code we write, but is also very easy to use, but pay attention to the following points:
① The parameters used by anonymous inner classes must be final;

②The anonymous inner class has no name, so it is impossible to have a constructor. It can only achieve the effect of a constructor through instance initialization.
Let's introduce an anonymous inner class written by myself, combined with the design pattern I learned - static factory pattern (of course it is not the 23 patterns written by GOF, but it is still very commonly used)


package com.huat.InnerClass;

/**
 * @author: 
 * @see功能介绍:
 * @vesion版本号:JDK1.8
 * 2018年1月13日
 */

interface Service {
    void method1();

    void method2();
}

interface ServiceFactory {
    Service getService();
}

class Implementation1 implements Service {

    private Implementation1() {

    }

    @Override
    public void method1() {
    System.out.println("Implementation1 method1");
    }

    @Override
    public void method2() {
    System.out.println("Implementation1 method2");
    }

    // 通过实现接口的匿名类
    public static ServiceFactory factory = new ServiceFactory() {

    @Override
    public Service getService() {
        return new Implementation1();
    }

    };

}

class Implementation2 implements Service {

    private Implementation2() {

    }

    @Override
    public void method1() {
    System.out.println("Implementation2 method1");
    }

    @Override
    public void method2() {
    System.out.println("Implementation2 method2");
    }

    // 通过实现接口的匿名类
    public static ServiceFactory factory = new ServiceFactory() {

    @Override
    public Service getService() {
        return new Implementation2();
    }

    };

}

public class Factories {

    public static void serviceConsumer(ServiceFactory f) {
    Service s = f.getService();
    s.method1();
    s.method2();
    }

    public static void main(String[] args) {
    serviceConsumer(Implementation1.factory);
    serviceConsumer(Implementation2.factory);

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325863685&siteId=291194637