【JavaSE】使用匿名内部类

在java中匿名内部类也是经常使用的,它不仅更加简化我们写的代码,使用起来还很顺手,但是要注意一下几点
①匿名内部类所使用的参数必须是final;

②匿名内部类因为没有名字,所以不可能有构造函数,只能通过实例初始化来达到一个构造器的效果。
下面就介绍一个自己写的匿名内部类,结合自己学到的设计模式–静态工厂模式(当然它并非是GOF写的23中模式,不过还是很常用的)


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);

    }
}

猜你喜欢

转载自blog.csdn.net/alearn_/article/details/80022980