匿名内部类--工厂

 

匿名内部类实现工厂。

interface Service {
    void method1();
    void method2();
}
interface ServiceFactory {
    Service getService();
}
class Implementation1 implements Service {
    private Implementation1() {}
    public void method1() {System.out.println("Implementation1 method1");}
    public void method2() {System.out.println("Implementation1 method2");}

    public static ServiceFactory factory(){
        return new ServiceFactory() {
            public Service getService() {
                return new Implementation1();
            }
        };
    }
}
class Implementation2 implements Service {
    private Implementation2() {}
    public void method1() {System.out.println("Implementation2 method1");}
    public void method2() {System.out.println("Implementation2 method2");}

    public static ServiceFactory factory = new ServiceFactory() {
        public Service getService() {
            return new Implementation2();
        }
    };
}

 

posted @ 2017-08-17 13:46  guodaxia  阅读(115)  评论(0编辑  收藏  举报