zoukankan      html  css  js  c++  java
  • Java 匿名类

    工厂方法

    匿名类与正规的继承相比有些受限,因为匿名类既可以扩展类,也可以实现接口,但不能两者兼备。如果实现接口,也就只能实现一个接口。

     1 package innerclasses;
     2 
     3 
     4 interface Service{
     5     void method1();
     6     void method2();
     7 }
     8 
     9 interface ServiceFactory{
    10     Service getService();
    11 }
    12 
    13 class Implementation1 implements Service{
    14     private Implementation1(){}
    15     public void method1(){
    16         System.out.println("Implemention1 method1");
    17     }
    18     public void method2(){
    19         System.out.println("Implemention1 method1");
    20     }
    21     //下面是匿名类
    22     public static ServiceFactory factory = new ServiceFactory(){
    23         public Service getService(){
    24             return new Implementation1();
    25         }
    26     };
    27 }
    28 
    29 class Implementation2 implements Service{
    30     private Implementation2(){}
    31     public void method1(){
    32         System.out.println("Implemention2 method1");
    33     }
    34     public void method2(){
    35         System.out.println("Implemention2 method2");
    36     }
    37     
    38     public static ServiceFactory factory = new ServiceFactory(){
    39         public Service getService(){
    40             return new Implementation2();
    41         }
    42     };
    43 }
    44 
    45 public class Factories{
    46     public static void serviceConsumer(ServiceFactory fact){
    47         Service s = fact.getService();
    48         s.method1();
    49         s.method2();
    50     }
    51     public static void main(String [] args){
    52         serviceConsumer(Implementation1.factory);
    53         serviceConsumer(Implementation2.factory);
    54     }
    55 }
    View Code

    结果:

    Implemention1 method1
    Implemention1 method1
    Implemention2 method1
    Implemention2 method2
  • 相关阅读:
    BZOJ 1452 Count(二维树状数组)
    BZOJ 1407 Savage(拓展欧几里得)
    BZOJ 1415 聪聪和可可(期望DP)
    BZOJ 1406 密码箱(数论)
    最大流小结
    UVA6531Go up the ultras
    二分图小结
    Codeforces Round #243 (Div. 1)
    图论模板集合
    zoj3416 Balanced Number
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3795147.html
Copyright © 2011-2022 走看看