java匿名内部类实现工厂方法模式

来源:互联网 发布:声音编辑软件中文版 编辑:程序博客网 时间:2024/05/23 10:30

先介绍一下匿名内部类:

public interface Contents {    int value();}public class Parcel7 {    public Contents contents(){//匿名类开始        return new Contents() {            private int i=11;            @Override            public int value() {                return i;            }        };//匿名类结束    }    public static void main(String[] args){        Parcel7 p=new Parcel7();        Contents c=p.contents();    }}//实际上匿名类就是用一个方法将返回值的生成与表示这个返回值的类的定义结合在一起。

上面代码相当于:

public interface Contents {    int value();}public class Parcel7b {    class MyContents implements Contents{        private int i=11;        public int value(){return i;}    }    public Contents contents(){        return new MyContents();    }    public static void main(String[] args){        Parcel7b p=new Parcel7b();        Contents c=p.contents();    }}

匿名内部类实现工厂方法模式:

interface Service {//抽象产品    void method1();    void method2();}interface ServiceFactory{//抽象工厂    Service getService();}class Implementation1 implements Service{//具体产品1    private Implementation1(){}    public void method1(){        System.out.println("Implementation1 method1");    }    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{//具体产品2    private Implementation2(){}    public void method1(){        System.out.println("Implementation2 method1");    }    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 fact){        Service s=fact.getService();//工厂生产产品        s.method1();        s.method2();    }    public static void main(String[] args){        serviceConsumer(Implementation1.factory);        serviceConsumer(Implementation2.factory);    }}

具体产品的构造器都是private,并且没有必要创建作为工厂的具名类。另外,你经常只需要单一的工厂对象,因此在本例中它被创建为Service实现中的一个static域。

阅读全文
0 0
原创粉丝点击