Design Pattern :Factory and Reflect in java

interface page
{
    void Render();
}
class pageA implements page
{
    @Override
    public void Render() {
         System.out.println("I am " + this.getClass().getName());
    }
}
class pageB implements page
{
    @Override
    public void Render() {
         System.out.println("I am " + this.getClass().getName());
    }
}
public class factorypatterndemo {
    page getPage(String pageName)
    {
        try {
                @SuppressWarnings("rawtypes")
                Class cls = Class.forName(pageName);
                try {
                    return (page)cls.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args)
    {
         System.out.println(pageA.class.getName());
         factorypatterndemo f = new factorypatterndemo();
         f.getPage("pageA").Render();
         f.getPage("pageB").Render();
    }
}

posted on 2015-02-11 21:55  tneduts  阅读(135)  评论(0编辑  收藏  举报

导航